Skip to content
Projets

À propos

AI commit message generator. Conventional commits, compose mode, and history rewrite via Claude/GPT APIs.

IA et apprentissage automatique

Comment ces chiffres sont mesurés

What you can do

  • Conventional commits — Generates properly formatted commit messages with type, scope, and past-tense summary (≤72 chars)
  • Automatic changelogs — Maintains CHANGELOG.md following Keep a Changelog format with monorepo support
  • Compose mode — Splits large staged changes into multiple logical atomic commits
  • Rewrite mode — Converts entire git history to conventional commits (with automatic backup)

Progression mesurée des étoiles

in 24h
0
in 7 days
+1
in 15 days
+2
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

lgit

LLM-powered git commit message generator

CI PyPI License Python

Generates conventional commits from git diffs using Claude AI or any OpenAI-compatible API.
Automatic changelog maintenance, multi-commit composition, history rewriting, and isolated rebases.


Features

  • Conventional commits — Generates properly formatted commit messages with type, scope, and past-tense summary (≤72 chars)
  • Automatic changelogs — Maintains CHANGELOG.md following Keep a Changelog format with monorepo support
  • Compose mode — Splits large staged changes into multiple logical atomic commits
  • Rewrite mode — Converts entire git history to conventional commits (with automatic backup)
  • Rebase — Preserves local merges by default, resolves provable conflicts without a model, and verifies a private result before publication
  • Map-reduce analysis — Parallel per-file analysis for large commits without truncation
  • Any LLM provider — Works with Anthropic, OpenAI, OpenRouter, or any OpenAI-compatible API

Quick Start

# Install
uv tool install lgit-cli

# Configure (pick one)
export LLM_GIT_API_KEY=your_anthropic_key                    # Direct Anthropic
export LLM_GIT_API_URL=https://openrouter.ai/api/v1          # OpenRouter
litellm --port 4000                                           # Local proxy (default)

# Use
git add .
lgit                    # Analyze, update changelog, commit
lgit --dry-run          # Preview without committing
lgit compose           # Split into multiple commits

Usage

Basic Commands

lgit                                # Analyze staged changes and commit
lgit --dry-run                      # Preview message without committing
lgit --copy                         # Copy message to clipboard
lgit -p                             # Commit and push
lgit -S                             # GPG sign the commit
lgit -s                             # Add Signed-off-by trailer
lgit --amend                        # Amend the previous commit
lgit > msg.txt                      # Save raw message to file (auto-detected pipe mode)
lgit --dry-run | git commit -F -    # Generate message and commit with custom git flags

# Modes
lgit --mode=unstaged                # Analyze unstaged changes, then stage all and commit
lgit --mode=commit --target=HEAD~1  # Analyze a specific commit

# Models
lgit -m opus                        # Use Opus for analysis (more capable)
lgit -m sonnet                      # Use Sonnet (default)

# Context
lgit Fixed regression from PR #123  # Add context via trailing text
lgit --fixes 123 456                # Add "Fixes #123, #456" to body
lgit --breaking                     # Mark as breaking change

Compose Mode

Split staged changes into multiple logical commits:

lgit compose                        # Propose and create atomic commits
lgit compose --preview              # Preview splits without committing
lgit compose --max-commits 5

Format Mode

Commit only the formatting-only part of pending changes (after running a formatter), without any LLM call:

lgit fmt                            # Commit as `style: reformatted N files`; other changes stay pending
lgit fmt --dry-run                  # List the files (partial ones keep other changes) and the message
lgit fmt --dry-run --explain        # Explain skipped files without committing

Format mode recognizes layout changes and selected formatter rewrites, including reordered import groups:

  • JS, TS, JSX, TSX: quote style, optional semicolons and arrow parentheses, sorted named imports, and text reflow that preserves rendered spaces. TypeScript also recognizes optional leading | and & in types.
  • Python: equivalent string literals and implicit string joins, redundant annotation and expression parentheses, and sorted import names.
  • Rust: nested use groups, continued strings, and braces around simple match-arm values.
  • Go: grouped imports, redundant expression parentheses, optional semicolons, and numeric literal case.
  • Data: JSON (including SARIF, notebooks, GeoJSON, glTF, web manifests, and Avro schemas), JSON with comments (including VS Code and Sublime settings), line-delimited JSON, YAML, and TOML. Known names such as .clang-format, Pipfile, and Cargo.lock are recognized without relying on a suffix.
  • Markdown: prose reflow, list and table layout, and formatting inside fences labeled with a supported language. Unlabeled or unknown snippets are kept verbatim.
  • CSS: rule, selector, and declaration layout that preserves selector and value tokens.
  • HTML: tag and attribute layout and whitespace between block elements. Inline spacing, preformatted text, and embedded script/style content are preserved.
  • KDL: layout and optional node terminators that preserve node structure and values.
  • Build and shell: sh/Bash, shared Zsh syntax, Fish, PowerShell, Dockerfile/Containerfile, Make, CMake, and Bazel/Starlark. Extensionless shell scripts are recognized by their shebang.
  • Infrastructure and configuration: Terraform/HCL, Nix, Protobuf and textproto, GraphQL, SQL, INI, EditorConfig, Git config and ignore/attribute files, dotenv, and Java properties.
  • Markup, styles, and docs: XML and related files (including SVG and MSBuild), SCSS/Sass/Less, MDX, Vue, Svelte, Astro, AsciiDoc, reStructuredText, and LaTeX. Significant whitespace and opaque embedded content are left alone.

Lexical formatting changes are also recognized in C/C++/C#, Java/Kotlin/Scala/Swift/Dart, and JSON5. Format mode leaves changes it can't prove equivalent pending, skips files with both staged and unstaged edits, and does not run commit hooks.

Use the lgit-format Git attribute to override detection for repository paths. Add rules to .gitattributes (shared) or .git/info/attributes (local only). Format names such as jsonc, yaml, shell, and textproto, or a supported suffix such as .tf, select the parser; -lgit-format disables detection.

config/*.app lgit-format=jsonc
vendor/** -lgit-format

Rewrite Mode

Convert repository history to conventional commits:

lgit rewrite                        # Rewrite full history (creates backup)
lgit rewrite --preview 10           # Preview first 10 commits
lgit rewrite --dry-run              # Show all changes without applying
lgit rewrite --start main~50        # Rewrite last 50 commits only
lgit rewrite --parallel 20          # 20 concurrent API calls

Rebase

lgit rebase origin/main --dry-run        # Plan from local refs; does not fetch
lgit rebase '@{upstream}'                # Use the current branch's configured upstream
lgit rebase refs/heads/old-base --onto refs/heads/new-base
lgit rebase /path/to/checkout:main       # Use that checkout's committed tip, not its edits
lgit rebase origin/main --context "Keep the new public API; port local callers"

compose, rewrite, fmt, test, rebase, resolve and verify-rebase are commands only in the first argument position. Put --dir and other options after the command. Use lgit -- compose ... (or lgit -- rebase ...) to pass those words as commit-message context.

A destination can be a ref or a commit ID. Use an explicit refs/heads/... to select a local branch when a short name could select a configured upstream instead. A real run can fetch the selected tracking ref; dry-run uses cached refs without checking remote freshness. Dry-run shows the pinned range and pending workspace changes without replay, generators, checks, or model calls. --onto makes the positional ref the cutoff instead of the destination. Nothing is pushed.

Local merges are preserved by default. Use --no-merges only if you explicitly want to discard their topology. To reorder two linear commits without changing their base:

base=$(git rev-parse HEAD~2)
plan=$(mktemp)
git rev-list --reverse "$base"..HEAD > "$plan"
# Swap the two lines in "$plan" with your editor, then preview:
lgit rebase "$base" --reorder "$plan" --dry-run
lgit rebase "$base" --reorder "$plan"

A reorder plan contains one full commit ID per line, not Git todo commands. Include each selected commit exactly once, including merges unless using --no-merges. The order must preserve merge dependencies. A pure reorder must reproduce the original tip tree and respect intermediate ownership. If a feature moves before an API migration, lgit checks affected callers against the earlier API, including lines Git merged cleanly. It restores deferred changes at their verified writer, not by replacing the final tree wholesale. These checks do not establish that each commit builds; configure a build check when you need one.

For an eligible linear series, Git merges each pick directly into a tree object. lgit verifies the intermediate result against its original change and rewritten parent before replaying the next pick, then checks out the verified tip once. If any pick needs a judgment, signing, or a worktree check, the native sequencer takes over from the original pinned inputs. Exact three-way resolutions, supported structural merges, and registered offline generators use no model. Workers get named conflict regions with nearby context, not several copies of every file. A rejected region can be retried without asking again about independent, accepted edits. If a decision spans commits or callers, the central model gets the relevant pinned history and earlier decisions; its ruling is checked on later commits, including files Git merged without a conflict. If the repository doesn't settle intent, the command pauses for your answer rather than picking a side.

Rebase requires a complete POSIX checkout. Git text/EOL settings such as core.autocrlf=input and eol=lf are not by themselves reasons to refuse. Staged blobs and raw unstaged bytes are tracked separately. Unchanged assets with external filters need not block replay: lgit leaves their live bytes alone and can use their stored pointers in the private checkout. An overlapping conversion it cannot preserve is reported by path; it will not run an untrusted filter to guess the answer. Active Git operations, unsupported indexes, submodules, and required hooks still get explicit preflight errors.

Results and recovery. Replay and conflict resolution happen in a private checkout. lgit carries staged edits, unstaged edits, and untracked files forward separately. It does not stage everything or reset the live checkout. A verified private handoff means the result is ready to inspect, not that your branch moved.

Publication. Without a configured publisher, lgit publishes with Git when HEAD is on a branch, isolation is independent (the default outside an ovnfs mount), and the live checkout has no staged, unstaged, or filter-protected changes. Untracked files are allowed and stay in place. While holding the branch's ref locks, lgit rechecks the live checkout, checks out only the changed paths (git read-tree -m -u), then moves the branch. The result is handed off instead if an ignored live file sits where the result adds a path, if live-only attributes change a changed path's checkout policy, or if any tracked path uses a filter driver (such as Git LFS), a working-tree encoding, or ident, because Git could run those conversions while rewriting the index. This checkout is not atomic. An interruption can leave some changed paths written; if Git had already installed the new index, lgit rebase --continue ID finishes moving the branch and lgit rebase --abort ID restores the previous files. A live checkout with local changes always gets a handoff: publishing content changes on top of local edits needs an authorized atomic workspace publisher.

  • 0: published, already up to date, or a successful dry-run or abort.
  • 1: fatal rebase error.
  • 2: pending, stale, or a verified private handoff. Read the reported status and transaction ID before continuing. Invalid command syntax also exits 2, with a usage error instead of a transaction.

If lgit reports unresolved paths, resolve and stage only the listed paths in the reported private checkout, then resume from the original repository with lgit rebase --continue ID. Leave the private HEAD and the rest of the index alone; don't run git rebase --continue yourself. For a pending decision, use lgit rebase --continue ID --context "...". IDs can be omitted only when there is a single matching transaction. If the original checkout changed, start a fresh plan instead of applying a stale result.

For a handoff, set private to the reported path and inspect it with git -C "$private" log -1, git -C "$private" diff --cached, git -C "$private" diff, and git -C "$private" status --short. Don't edit a verified handoff: that invalidates it for publication. You can configure an authorized publisher and rerun lgit rebase --continue ID to attempt publication. Start a new transaction if you change the verification checks. lgit rebase --abort ID cleans up the owned transaction after any required recovery; it doesn't undo an already published rebase.

Resolve an existing conflict

lgit resolve --dry-run                       # Explain the unmerged paths; no model or file writes
lgit resolve src/client.py docs/             # Stage resolutions only for these literal paths
lgit resolve --context "Keep the new timeout semantics for local callers"

Use resolve in a checkout where Git has already stopped: a merge, rebase, cherry-pick, revert, or applying a stash. With no paths, it considers all unmerged index entries, including conflicts without textual markers. Paths are relative to --dir (default: the current directory). -- separates options from a filename beginning with a dash.

resolve never commits, continues or aborts the Git operation, or drops a stash. Review the staged result with git diff --cached. Exit 2 means there is still work to do: check the listed paths before continuing. Independent resolutions may already be staged. If the index or working bytes changed during resolution, the earlier suggestion is not permission to overwrite them.

To authorize an existing generator or codec for this command, include "resolve" in its phases in your trusted rebase configuration. The default rebase registrations alone do not grant permission to stage live outputs. A path selection is not permission to stage unrelated generated siblings.

Verify a rebase someone else performed

lgit verify-rebase "$old_tip"                                   # Audit old tip against HEAD
lgit verify-rebase "$old_tip" --old-base "$fork" --onto "$base" # Supply exact range boundaries
lgit verify-rebase "$old_tip" --new-tip "$candidate" --onto "$base" --json

This command reads commit objects. It doesn't fetch, switch branches, stage anything, or call a model. It checks the two commit ranges, not just their tip diff: a matching tip tree can hide a dropped merge or a change assigned to the wrong commit. If it cannot establish the range boundaries, give it the original cutoff (--old-base) and the destination (--onto). Exit 0 means the stated audit passed, 2 means differences or insufficient evidence, and 1 means a command/input error. A passing content and topology audit is not a build or test result.

Profiling Trace

Write detailed tracing spans and HTTP timing events to a JSONL file:

lgit --trace-output /tmp/lgit-profile.jsonl --dry-run
LLM_GIT_TRACE_FILE=/tmp/lgit-profile.jsonl lgit compose

Each span close event includes busy/idle timing from tracing-subscriber; API events also record TTFT, total response time, status, and response size.

Automatic Changelog

lgit automatically maintains CHANGELOG.md files when committing:

  • Auto-detection — Finds all CHANGELOG.md files in your repository
  • Monorepo support — Routes changes to the correct changelog based on file paths
  • Deduplication — Skips entries semantically similar to existing ones
  • Category mapping — Maps commit types to sections (Added, Fixed, Changed, etc.)
project/
├── CHANGELOG.md              ← covers: src/, docs/
├── packages/
│   ├── core/
│   │   └── CHANGELOG.md      ← covers: packages/core/**
│   └── cli/
│       └── CHANGELOG.md      ← covers: packages/cli/**

Disable with --no-changelog or changelog_enabled = false in config.

When staged changes have a changelog boundary, one synthesis call generates the commit analysis and all applicable changelog updates together. Compose uses the same synthesis for each already-planned group; grouping and staging are unchanged. Large inputs reuse per-file map observations, and valid summaries avoid a separate summary call.

Summary repair/rewrite, authored-entry protection, existing-entry revisions, and staged/worktree isolation still apply. Malformed shared output falls back to separate generation. --dry-run, commit/unstaged analysis, and --no-changelog retain their existing generation paths.

Prompt overrides remain explicit: a relevant analysis.md, fast.md, map.md, reduce.md, or changelog.md override keeps separate calls unless the override directory also supplies synthesis.md.

Configuration

Create ~/.config/llm-git/config.toml:

# API
api_base_url = "http://localhost:4000"    # Default: LiteLLM proxy
api_key = "sk-..."                        # Or use LLM_GIT_API_KEY env var

# Model — any role accepts a `;`-separated fallback chain, tried left to right
analysis_model = "claude-sonnet-4.5"      # Diff analysis / classification
summary_model = "claude-haiku-4-5"        # Summary line generation
map_model = ""                            # Per-file map phase; empty = summary_model
fast_model = "flash-lite;haiku"           # Fast mode; falls back when the primary stalls

# Commit message limits
summary_guideline = 72                    # Target length
summary_soft_limit = 96                   # Triggers retry
summary_hard_limit = 128                  # Absolute max

# Features
changelog_enabled = true
auto_fast_threshold_lines = 200           # Auto-use fast mode for small diffs; 0 disables
map_reduce_enabled = true                 # Parallel analysis for large commits
disable_git_background_features = true    # Disables fsmonitor/untrackedCache for lgit subprocesses

# Typed judgments (TypeSafe jev, ~$0.04 per million input tokens, ~1s per round trip).
# With a key: mechanical follow-through hunks (imports, call sites, formatting, lockfiles)
# are pruned from analysis prompts and the rest get a per-hunk type hint; compose binds
# hunks to groups by judgment instead of the analysis model; changelog generation is
# skipped for changes judged not user-visible and paraphrased duplicate entries are
# dropped. Shared commit/changelog synthesis does not require a judge key.
judgment_api_key = ""                     # Or TYPESAFE_API_KEY env var; `!cmd` runs a command
judgment_model = "jev-latest"
mechanical_hunk_threshold = 0.7           # Prune hunks judged mechanical with >= this probability
mechanical_prune_min_tokens = 5000        # Skip pruning below this diff size (round trip not worth it)
mechanical_prune_min_model_rate = 1.0     # ...and unless the analysis model bills >= this $/M (judging costs ~$0.08/M of diff)
changelog_gate_threshold = 0.3            # Skip the changelog model below this user-visibility; 0 disables

# Commit signing
gpg_sign = false                          # GPG sign commits by default (-S)
signoff = false                           # Add Signed-off-by trailer by default (-s)

Rebase Configuration

Set rebase options in the same user TOML file. lgit does not discover command registrations in the replayed tree. Only use --config or LLM_GIT_CONFIG with a file you trust.

# Keep these top-level settings above the first TOML table.
rebase_worker_model = ""    # Defaults to fast_model, then summary_model
rebase_oracle_model = ""    # Defaults to analysis_model
rebase_parallelism = 6      # Positive maximum for concurrent conflict workers
rebase_judge_min_files = 0  # Off; optionally hint at grouping large batches of escalations

# Only for an authorized workspace backend with atomic activation and recovery:
# rebase_publisher = ["/absolute/path/to/workspace-publisher"]

The two rebase model roles accept the same ;-separated provider fallback chains as other roles. A worker handles scoped local conflicts; the oracle handles decisions that affect multiple edits or commits. When a pure reorder leaves only exact Git objects to restore at their last writer, the oracle confirms or declines those objects; workers do not rewrite them. This confirmation uses the rebase-endpoint.md prompt override and the same oracle model. A transport fallback stays within its role. A model reply that fails a controller check gets one correction round naming that check; a second failure stops the rebase. Rebase does not accept the commit-message -m override. Mechanical resolutions do not initialize model or judge clients.

By default, lgit runs no project generator, codec, or test command during replay. Register commands explicitly for the absolute path of the original checkout, and trust any repository code they load, including code in the commits you are replaying. Commands use explicit argument arrays, not shell snippets or model-provided commands.

[[rebase_checks]]
repo = "/home/me/project"
name = "parser unit tests"
paths = ["src/parser", "tests/test_parser.py"]
argv = ["/usr/bin/python3", "-m", "unittest", "discover", "-s", "tests", "-p", "test_parser.py"]
cwd = "."
timeout = 60

[[rebase_drivers.generators]]
repo = "/home/me/project"
allow_repo_code = true
argv = ["/usr/bin/python3", "tools/build_catalog.py"]
cwd = "."
sources = ["catalog/**", "tools/build_catalog.py"]
outputs = ["generated/catalog.json"]
validator = "json"

This example assumes the generator reads the declared inputs and writes generated/catalog.json. Checks run on the exact private candidate when their repository-relative path prefixes are affected. Producers use declared staged inputs and run offline in a disposable sandbox; unavailable isolation or undeclared output changes block automatic resolution. Use absolute executable paths, explicitly authorize any additional tools or runtime paths needed by the sandbox, and supply already-installed offline dependencies with assets when needed. A registered codec instead uses [[rebase_drivers.codecs]] with an exact path, argv, sources, a supported bridge, and its module (for example, bridge = "omp_catalog" for the OMP catalog format). It must also name the absolute repo and opt in with allow_repo_code = true.

A publisher that only installs Git blobs cannot reproduce noncanonical raw checkout bytes. If the configured publisher cannot represent the prepared result exactly, lgit leaves the result private.

rebase_publisher is an external backend, not a list of Git commands to run on the live checkout. lgit appends publish REQUEST.json or recover REQUEST.json to the configured argv and invokes it from the transaction state directory. The version 1 request names transaction_id, source_root, checkout, expected_snapshot, prepared_manifest, prepared_index, and candidate (oid, tree, index_tree, worktree_tree). It requires the backend to preserve ambient paths and retain the transaction journal. The backend must atomically activate the ref, index, and files only if the live pins still match. Return a stdout JSON object with status (published, stale, or unsupported; recovery may also return not_applied) and detail. lgit cross-checks a published receipt against the installed ref, index, and files. If the command fails or returns an invalid reply, the journal remains pending for recovery. Without an authorized backend for a content-changing result, lgit keeps the verified result private.

Provider Examples

Anthropic Direct:

api_base_url = "https://api.anthropic.com/v1"
api_key = "sk-ant-..."

OpenRouter:

api_base_url = "https://openrouter.ai/api/v1"
api_key = "sk-or-..."
analysis_model = "anthropic/claude-sonnet-4.5"
summary_model = "anthropic/claude-haiku-4-5"

OpenAI:

api_base_url = "https://api.openai.com/v1"
api_key = "sk-..."
analysis_model = "gpt-4o"
summary_model = "gpt-4o-mini"

Judgments (optional, any provider above):

judgment_api_key = "!cat ~/.secrets/typesafe"   # key from https://console.typesafe.ai/

Set LLM_GIT_JUDGMENT_DISABLED=1 to switch judgments off without removing the key.

The client uses the same response formats across OpenRouter, LiteLLM, Anthropic, and OpenAI endpoints: markdown/plain text for individual operations and a validated JSON object for shared commit/changelog synthesis.

Commit Types

Customize commit type classification:

[types.feat]
description = "New public API or user-observable behavior change"
diff_indicators = ["pub fn", "pub struct", "export function"]

[types.fix]
description = "Fixes incorrect behavior"
diff_indicators = ["unwrap() → ?", "bounds check", "error handling"]

[types.refactor]
description = "Internal restructuring with unchanged behavior"
hint = "If behavior changes, use feat instead."

Changelog Categories

[[categories]]
name = "Breaking"
header = "Breaking Changes"
match.body_contains = ["breaking", "incompatible"]

[[categories]]
name = "Added"
match.types = ["feat"]

[[categories]]
name = "Fixed"
match.types = ["fix"]

[[categories]]
name = "Changed"
default = true

Environment Variables

Variable Description Default
LLM_GIT_API_URL API endpoint http://localhost:4000
LLM_GIT_API_KEY API key none
LLM_GIT_CONFIG Config file path ~/.config/llm-git/config.toml
LLM_GIT_VERBOSE Debug output false
LLM_GIT_TRACE_FILE JSONL profiling trace output path none
LGIT_REBASE_ISOLATION Private rebase checkout provider (independent or ovnfs) Auto-detect ovnfs under OVNFS_MOUNT; otherwise independent

Installation

From PyPI

uv tool install lgit-cli    # recommended
pipx install lgit-cli       # or
pip install lgit-cli

From source

git clone https://github.com/can1357/llm-git.git
cd llm-git
uv tool install .

Prerequisites

  • Python 3.14+
  • Git
  • API access (Anthropic, OpenAI, OpenRouter, or local LiteLLM proxy)

License

MIT

Explorer des projets similaires

Chargement…