Skip to content
thorspherePublic

About

Minimalist Go CLI tool for generating conventional git commit messages from staged diffs with AI.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

134 Commits

Folders and files

Repository files navigation

tscommit

PkgGoDev GitHub go.mod Go version GitHub release (latest by date) GitHub Top Language CodeFactor OSS Lifecycle


Minimalist Go CLI tool for generating conventional git commit messages from staged diffs with AI.


Package tscommit generates conventional git commit messages from diffs via a configured AI provider. It is a component-agnostic library: the AI provider API key is read from the environment, and no state is persisted locally. The non-interactive generation core (Generator) is reusable by any service or workflow, while an optional interactive CLI layer (Run/RunContext) drives user review and creates the commit.


Features

  • Conventional Commits output: strict <type>(<scope>)[!]: <description> headers (72-character limit, imperative mood, mandatory scope) with a 72-column body explaining WHAT and WHY, and optional trailers such as Refs #<issue> or BREAKING CHANGE:.
  • Generation from diffs: generates messages from unified diffs (the CLI feeds git diff --staged -W) and summarizes the dominant intent rather than listing files.
  • Self-correcting generation: generated messages are validated against the format rules; invalid or truncated output is fed back to the model with corrective feedback and regenerated.
  • Structured AI envelopes & calibrated confidence: decodes structured JSON responses (findings and confidence) via tsaiclient.Client.CompleteJSON, scores confidence against a four-tier diff-clarity rubric (0%–100%) returned in Message.Confidence and displayed in the interactive review prompt (omitted once edited), and strips any stray markdown fences or wrapper quotes from the message.
  • Completion metadata for metering: Message also reports the serving Model, the TotalTokens billed across all generation attempts, and the Cost in USD when the provider reports it, ready for logging and metering.
  • Interactive review loop: accept, edit in $EDITOR, regenerate, or cancel before anything is committed. User-edited messages are authoritative and never re-validated.
  • Breaking-change awareness: prominent warning when the message carries a Conventional Commits breaking-change marker.
  • Large-diff handling: the CLI truncates staged diffs at 30,000 characters (runes) with an explicit truncation marker, keeping prompts within the model's context window. Non-interactive callers bound diff size themselves (e.g. an HTTP request-body limit) before calling Generate.
  • Prompt-cache friendly: one sticky session ID per run so retries and regenerations reuse the provider endpoint and prompt cache.
  • Graceful cancellation: Ctrl-C or SIGTERM aborts cleanly at any step.
  • Library-friendly: the interactive workflow is available programmatically via tscommit.Run and tscommit.RunContext, and the non-interactive generation core via tscommit.Generator.

How It Works

  1. Read the staged diff (the CLI truncates it to 30,000 characters if needed).
  2. Send the diff to the configured AI provider with a strict Conventional Commits JSON envelope prompt; decode the structured response, validate the commit message, and retry format/truncation violations with feedback.
  3. In the interactive workflow, present the message and model confidence and ask the user to commit, edit, regenerate, or cancel.
  4. On commit, create the git commit with the reviewed message.

Getting Started

Requires Go 1.27 or later, git, and an OpenRouter API key.

There is no prebuilt binary; the CLI lives in cmd/cli and is built from source.

Clone the repository and build the CLI:

git clone https://github.com/thorsphere/tscommit.git
cd tscommit
go build -o tscommit ./cmd/cli

Or run it directly without building:

go run ./cmd/cli

Provide your API key via the environment (twelve-factor style):

export OPENROUTER_API_KEY=sk-or-...

Stage your changes in the repository you want to commit in, then run the binary (./tscommit, or tscommit if you put it on your PATH):

git add -A
./tscommit

You will be shown the generation summary, the generated message, and asked what to do:

Diff: 1420 chars | Model: google/gemini-3-flash-preview (low) | Tokens: 412 | Cost: $0.00031

feat(git): add staged-diff truncation

Large diffs previously overflowed the prompt window. Truncate at 30k
characters so hunks stay parseable.

Confidence: 78%

Apply this commit? [Y/e/r/n] (Y=commit, e=edit, r=regenerate, n=cancel):
  • commit: create the git commit with the shown message.
  • edit: open the message in $EDITOR; the edited text is used as-is (and the AI summary and confidence lines are omitted on re-prompt).
  • regenerate: ask the model for a fresh message and confidence score for the same diff.
  • cancel: abort without committing.

Confidence Score Rubric

The model scores its confidence (0.0–1.0, displayed as 0%–100%) against the staged diff:

Score Meaning
85%–100% Small, self-contained diff with one unambiguous intent and explicit WHY in comments, tests, or error messages.
65%–84% Clear WHAT, but WHY/motivation is inferred from code context or several related files are touched.
40%–64% Large or multi-concern diff, ambiguous scope/type, missing context, or uncertain breaking-change impact.
0%–39% Truncated diff (... (truncated)), generated/opaque changes, or intent is mostly guesswork.

Configuration

All configuration comes from environment variables; there are no config files.

Variable Required Description
OPENROUTER_API_KEY yes OpenRouter API key used by the AI client. Read by the CLI at startup; missing key fails fast with a clear error.
EDITOR no Editor opened for the edit action (inherited from your shell/git setup).

Generation defaults are fixed for consistency: max 16,000 completion tokens, temperature 0.3, low reasoning effort, and a 2-minute request timeout.


API reference

The root package exposes both the interactive workflow and the non-interactive generation core as a library:

// Run executes the tscommit workflow with a background context.
func Run() error

// RunContext executes the tscommit workflow with the provided context.
func RunContext(ctx context.Context) error

// Config carries the AI provider settings for commit message generation:
// the model identifier and the reasoning effort level. The zero value is
// not usable; construct instances with NewConfig.
type Config struct {
    model           string // The model identifier passed to the AI provider.
    reasoningEffort string // The reasoning effort level passed to the AI provider.
}

// NewConfig returns a Config populated with the package defaults: the
// default model identifier and the default reasoning effort level.
func NewConfig() *Config

// WithModel sets the model identifier, trimmed of surrounding whitespace,
// and returns cfg.
func (cfg *Config) WithModel(model string) *Config

// WithReasoningEffort sets the reasoning effort level, trimmed of
// surrounding whitespace, and returns cfg.
func (cfg *Config) WithReasoningEffort(effort string) *Config

// Model returns the configured model identifier ("" when cfg is nil).
func (cfg *Config) Model() string

// ReasoningEffort returns the configured reasoning effort level ("" when
// cfg is nil).
func (cfg *Config) ReasoningEffort() string

// NewGenerator returns a Generator configured with cfg and the environment
// API key alongside a freshly minted sticky routing key. cfg must be
// non-nil; pass at least NewConfig().
func NewGenerator(cfg *Config) (*Generator, error)

// Message holds a generated Conventional Commits message, its model
// confidence score, and completion metadata (Model, TotalTokens, Cost).
type Message struct {
    Text        string  `json:"text"`         // The generated commit message.
    Confidence  float64 `json:"confidence"`   // The model confidence score in [0, 1].
    Model       string  `json:"model"`        // The serving model identifier; empty if unreported.
    TotalTokens int     `json:"total_tokens"` // The total tokens billed across attempts.
    Cost        float64 `json:"cost"`         // The completion cost in USD across attempts.
}

// Generate returns a validated Conventional Commits Message for diff; the
// Message carries the commit text, the model confidence score, the serving
// model, the total billed tokens, and the completion cost.
func (g *Generator) Generate(ctx context.Context, diff string) (Message, error)

Typical embedding of the interactive workflow:

package main

import (
    "context"

    "github.com/thorsphere/tscommit"
)

func main() {
    if err := tscommit.RunContext(context.Background()); err != nil {
        panic(err)
    }
}

Typical non-interactive use of the generation core (e.g. from a service handler that has already bounded the request body size):

package main

import (
    "context"
    "fmt"

    "github.com/thorsphere/tscommit"
)

func main() {
    gen, err := tscommit.NewGenerator(tscommit.NewConfig())
    if err != nil {
        panic(err)
    }
    msg, err := gen.Generate(context.Background(), diff)
    if err != nil {
        panic(err)
    }
    fmt.Println(msg.Text)
}

See the Go Package Documentation for the complete reference.


Known Limitations

  • Diffs longer than 30,000 characters are truncated by the CLI (marked with a truncation marker); hunks beyond the limit are not described.
  • Non-interactive callers must bound diff size before calling Generate (e.g. reject oversized request bodies with 400 Bad Request in a service handler); Generate does not truncate.
  • Only staged changes are considered — unstaged or untracked work is invisible to the generator.
  • The CLI is interactive and expects a TTY for prompting and editing; it is not intended for unattended CI use.
  • Only the OpenRouter provider is supported, via tsaiclient.
  • Messages you edit yourself are intentionally not re-validated. Your text is authoritative.
  • AI-generated output quality and self-reported confidence scores depend on the underlying model; envelope/schema violations fail immediately, while message-format and truncation violations are retried once with feedback before failing.

Documentation & Resources


⚖️ License & Commercial Usage

Copyright (c) 2026 thorsphere. All rights reserved.

This project is licensed under the Functional Source License v1.1 (FSL-1.1-ALv2).

  • The use, modification, and redistribution of this Go package is completely free for private, educational, non-commercial, and internal purposes.
  • If you are a company or institution looking to use this package in a commercial product, service, or business environment, you must secure a commercial license.
  • Each version of this software automatically converts to the fully open-source Apache License, Version 2.0 on the second anniversary of its release.

For full details, please see the LICENSE file.

💼 Commercial Licensing & Inquiries

To purchase a commercial license or discuss support options, please reach out directly:

  • 📩 Contact: business at thorsphere dot com
  • 💬 Response Time: Usually within a couple of business days.

Please include your company name and a brief overview of your use case so I can provide the right licensing details.

About

Minimalist Go CLI tool for generating conventional git commit messages from staged diffs with AI.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Contributors

Languages