Skip to content

Commit

commit

GitCommitTool — batched atomic commits with commit-hook handling.

GitCommitTool

Bases: AXMTool

Execute one or more atomic commits in a single call.

Each commit in the batch is processed sequentially: stage files, run git commit (the repo's commit hooks fire automatically), and capture the result. If a commit fails (e.g. a hook rejects it), processing stops and the error is returned alongside any commits that already succeeded.

When a commit hook auto-fixes files (e.g. ruff --fix), the tool automatically re-stages and retries the commit once.

Verdict-Carrying Patch invariant — when a hook mutates staged content on the autofix-retry path, ToolResult.data reports exactly which files changed under hook_autofixed_files: list[str] (repo-root relative). The field is always present: it is an empty list on the clean path (no hooks, or no mutation) and never None. This lets a consumer see that the patch it committed is not byte-for-byte the patch it staged — the commit still carries a truthful verdict of what landed.

The hook runner is whatever the repo installs at .git/hooks/pre-commit (pre-commit OR prek); axm-git never invokes the runner directly — git does.

Registered as git_commit via axm.tools entry point.

Source code in packages/axm-git/src/axm_git/tools/commit.py
Python
class GitCommitTool(AXMTool):
    """Execute one or more atomic commits in a single call.

    Each commit in the batch is processed sequentially: stage files,
    run ``git commit`` (the repo's commit hooks fire automatically), and
    capture the result.  If a commit fails (e.g. a hook rejects it),
    processing stops and the error is returned alongside any commits
    that already succeeded.

    When a commit hook auto-fixes files (e.g. ruff ``--fix``),
    the tool automatically re-stages and retries the commit once.

    **Verdict-Carrying Patch invariant** — when a hook mutates staged
    content on the autofix-retry path, ``ToolResult.data`` reports exactly
    which files changed under ``hook_autofixed_files: list[str]`` (repo-root
    relative). The field is *always present*: it is an empty list on the
    clean path (no hooks, or no mutation) and never ``None``. This lets a
    consumer see that the patch it committed is not byte-for-byte the patch
    it staged — the commit still carries a truthful verdict of what landed.

    The hook runner is whatever the repo installs at
    ``.git/hooks/pre-commit`` (pre-commit OR prek); axm-git never
    invokes the runner directly — git does.

    Registered as ``git_commit`` via axm.tools entry point.
    """

    expose_directly = True
    domain = "git"
    tags = frozenset({"commit", "stage", "conventional"})

    @property
    def name(self) -> str:
        """Tool name used for MCP registration."""
        return "git_commit"

    DEPENDENCY_ENVIRONMENT_VERSION: ClassVar[int] = 1
    """Versioned capability: execute consumes the declared dependency runtime."""

    def execute(
        self,
        *,
        path: str = ".",
        commits: list[dict[str, object]] | None = None,
        profile: str | None = None,
        strict: bool = False,
        dependency_environment: Mapping[str, object]
        | DependencyEnvironment
        | None = None,
        **kwargs: object,
    ) -> ToolResult:
        """Commit with an optional explicit, invocation-local dependency runtime.

        The interpreter stays lexical; candidate sources precede the declared
        dependency paths. The environment applies to every subprocess and retry,
        then is restored even after an exception. Invalid contracts refuse
        before staging. This transports an environment; it does not certify
        arbitrary hooks as bootstrap-free or change their veto/autofix semantics.
        """
        from axm_git.core.commit_environment import (
            commit_environment,
        )
        from axm_git.core.commit_environment import (
            dependency_environment as resolve_environment,
        )

        try:
            environment = resolve_environment(
                Path(path).resolve(), dependency_environment
            )
        except ValueError as exc:
            error = str(exc)
            data: dict[str, object] = {
                "dependency_environment": {"status": "invalid", "version": 1}
            }
            return ToolResult(
                success=False,
                error=error,
                data=data,
                text=render_failure_text(error=error, data=data),
            )
        with commit_environment(environment):
            return self._execute_batch(
                path=path, commits=commits, profile=profile, strict=strict, **kwargs
            )

    def _execute_batch(
        self,
        *,
        path: str = ".",
        commits: list[dict[str, object]] | None = None,
        profile: str | None = None,
        strict: bool = False,
        **kwargs: object,
    ) -> ToolResult:
        """Execute batched commits.

        Args:
            path: Project root (required).
            commits: List of commit specs, each a dict with keys:
                - ``files`` (list[str]): Files to stage.
                - ``message`` (str): Commit summary line.
                - ``body`` (str, optional): Commit body.
            profile: Optional identity profile name. Overrides
                schedule-based resolution from ``git-profiles.toml``.
            strict: When ``True``, a non-Conventional-Commit message is a
                hard failure instead of a warning. Defaults to ``False``
                (warn-by-default guardrail).

        Returns:
            ToolResult with a list of committed results, an ``author`` key
            (``{name, email}`` or ``None``), and ``hook_autofixed_files``
            (``list[str]``, repo-root relative) naming any staged files a
            commit hook mutated during the autofix-retry — always present,
            ``[]`` when no hook auto-fixed anything.
        """
        resolved = Path(path).resolve()
        commit_list: list[dict[str, object]] = commits or []
        total = len(commit_list)

        if not commit_list:
            error = "No commits provided"
            return ToolResult(
                success=False,
                error=error,
                text=render_failure_text(error=error, data=None),
            )

        try:
            # Fail fast with suggestions if not a git repo
            check = run_git(["rev-parse", "--git-dir"], resolved)
            if check.returncode != 0:
                repo_err = not_a_repo_error(check.stderr, resolved)
                return ToolResult(
                    success=repo_err.success,
                    error=repo_err.error,
                    data=repo_err.data,
                    text=render_failure_text(
                        error=repo_err.error or "", data=repo_err.data
                    ),
                )

            # Resolve identity once for the entire batch
            identity = resolve_identity(resolved, profile_override=profile)
            identity_args = author_args(identity)

            results: list[dict[str, object]] = []
            autofixed: list[str] = []

            for i, spec in enumerate(commit_list):
                failure = _process_single_commit(
                    spec,
                    i + 1,
                    identity_args,
                    resolved,
                    results,
                    total,
                    autofixed,
                    strict=strict,
                )
                if failure:
                    return failure
        except subprocess.TimeoutExpired as exc:
            return timeout_error_result(exc)

        data = {
            "results": results,
            "total": len(results),
            "succeeded": len(results),
            # Verdict-Carrying Patch invariant: the paths a commit hook
            # auto-fixed during the re-stage + retry (deduplicated, sorted);
            # always present, ``[]`` on the clean path (AC1/AC2).
            "hook_autofixed_files": sorted(set(autofixed)),
            "author": (
                {"name": identity.name, "email": identity.email} if identity else None
            ),
        }
        return ToolResult(success=True, data=data, text=render_text(data))
DEPENDENCY_ENVIRONMENT_VERSION = 1 class-attribute

Versioned capability: execute consumes the declared dependency runtime.

name property

Tool name used for MCP registration.

execute(*, path='.', commits=None, profile=None, strict=False, dependency_environment=None, **kwargs)

Commit with an optional explicit, invocation-local dependency runtime.

The interpreter stays lexical; candidate sources precede the declared dependency paths. The environment applies to every subprocess and retry, then is restored even after an exception. Invalid contracts refuse before staging. This transports an environment; it does not certify arbitrary hooks as bootstrap-free or change their veto/autofix semantics.

Source code in packages/axm-git/src/axm_git/tools/commit.py
Python
def execute(
    self,
    *,
    path: str = ".",
    commits: list[dict[str, object]] | None = None,
    profile: str | None = None,
    strict: bool = False,
    dependency_environment: Mapping[str, object]
    | DependencyEnvironment
    | None = None,
    **kwargs: object,
) -> ToolResult:
    """Commit with an optional explicit, invocation-local dependency runtime.

    The interpreter stays lexical; candidate sources precede the declared
    dependency paths. The environment applies to every subprocess and retry,
    then is restored even after an exception. Invalid contracts refuse
    before staging. This transports an environment; it does not certify
    arbitrary hooks as bootstrap-free or change their veto/autofix semantics.
    """
    from axm_git.core.commit_environment import (
        commit_environment,
    )
    from axm_git.core.commit_environment import (
        dependency_environment as resolve_environment,
    )

    try:
        environment = resolve_environment(
            Path(path).resolve(), dependency_environment
        )
    except ValueError as exc:
        error = str(exc)
        data: dict[str, object] = {
            "dependency_environment": {"status": "invalid", "version": 1}
        }
        return ToolResult(
            success=False,
            error=error,
            data=data,
            text=render_failure_text(error=error, data=data),
        )
    with commit_environment(environment):
        return self._execute_batch(
            path=path, commits=commits, profile=profile, strict=strict, **kwargs
        )