commit

package
v0.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package commit turns repository state into one validated Git commit.

It owns the deterministic half of /commit: deciding the exact candidate scope, asking the dedicated commit model for text, validating that text, and executing exactly the approved commit. The model never receives a tool, a shell, or a path to the index; its output is untrusted proposal data.

Index

Constants

View Source
const (
	// MaxSubjectRunes bounds the complete first line.
	MaxSubjectRunes = 36
	// MaxBulletRunes bounds one complete body line, including "- ".
	MaxBulletRunes = 50
	// MaxBullets bounds the body so a proposal stays reviewable.
	MaxBullets = 5
)

Length limits are measured in Unicode code points (runes), not bytes and not terminal cells. A rune is what a human counts as one character; bytes would unfairly shorten non-ASCII text, and display width depends on the terminal font. The contract is one number everywhere.

View Source
const DefaultProposalTimeout = 5 * time.Minute

DefaultProposalTimeout bounds one COMMIT proposal request.

The timeout is a completion-time budget, not a token budget: a reasoning model may spend a long time producing hidden tokens before the first visible delta, and a queued free endpoint can add provider-side waiting on top of that. The old two-minute deadline was shorter than that legitimate window and surfaced as "the COMMIT model request timed out" for requests that were still generating.

Five minutes keeps a bounded interactive wait while leaving room for 8192 reasoning tokens and provider queueing. It is deliberately below the transport's ten-minute HTTP ceiling, so a genuinely stuck connection is reported as a COMMIT timeout instead of being killed by the HTTP client. The user can cancel at any time; the deadline only bounds how long a request may run unattended.

View Source
const DefaultProposalTokens = 1024

DefaultProposalTokens is the dedicated COMMIT completion budget.

A complete message is roughly 100 tokens, so this cap is a guardrail rather than a target. It is deliberately far below the coding-turn ceiling: COMMIT proposes text and does no reasoning over the repository. A model whose reasoning cannot be disabled may still spend hidden tokens here; that case is reported as ErrModelTruncated rather than accepted as a partial message. The value is clamped to the model's own ceiling where the catalog knows it.

Variables

View Source
var (
	// ErrNoChanges means the repository has nothing ohgo may commit.
	ErrNoChanges = errors.New("commit: no changes to commit")
	// ErrStagedExcluded means the index already contains a path ohgo treats
	// as internal or ignored. Committing the index would include it, so the
	// only safe action is to stop and let the human decide.
	ErrStagedExcluded = errors.New("commit: staged changes include excluded paths")
	// ErrTooManyChanges keeps one reviewable proposal bounded.
	ErrTooManyChanges = errors.New("commit: too many changed paths")
)

Errors that stop /commit before it asks the model or mutates anything.

View Source
var (
	// ErrProposalTimeout is the cause recorded when the bounded COMMIT
	// deadline expires.
	ErrProposalTimeout = errors.New("commit: proposal request deadline expired")
	// ErrCancelledByUser is the cause recorded when the human cancels /commit.
	ErrCancelledByUser = errors.New("commit: proposal cancelled by user")
	// ErrSessionClosed is the cause recorded when the session is left or quit.
	ErrSessionClosed = errors.New("commit: session closed")
	// ErrSuperseded is the cause recorded when a newer /commit replaces an
	// in-flight proposal.
	ErrSuperseded = errors.New("commit: proposal superseded")
)

Request causes. They are attached to the proposal context so a failure can say why it stopped instead of collapsing user cancellation, session shutdown, and a real deadline into one generic timeout.

View Source
var (
	// ErrStateChanged means HEAD, the index, or the worktree changed after the
	// proposal. The commit is aborted; the change is never absorbed.
	ErrStateChanged = errors.New("commit: repository state changed after proposal")
	// ErrStagingMismatch means the index does not hold exactly the approved
	// paths and content.
	ErrStagingMismatch = errors.New("commit: staged content does not match the approved scope")
	// ErrCommitVerification means Git reported success but the resulting
	// commit does not match the approved message or parent.
	ErrCommitVerification = errors.New("commit: committed result failed verification")
)

Errors that describe a refused or failed execution.

View Source
var (
	// ErrModel means the transport or provider failed before returning text.
	ErrModel = errors.New("commit: commit model request failed")
	// ErrModelEmpty means the model finished without any visible text.
	ErrModelEmpty = errors.New("commit: commit model returned an empty response")
	// ErrModelTruncated means the output budget was exhausted before any
	// visible text arrived. A reasoning model can spend the whole budget on
	// hidden tokens, which is why this is distinct from a genuinely empty
	// reply.
	ErrModelTruncated = errors.New("commit: commit model output was truncated")
	// ErrModelTimeout means the bounded COMMIT request deadline expired.
	ErrModelTimeout = errors.New("commit: commit model request timed out")
	// ErrModelProviderTimeout means the provider or transport timed out while
	// the COMMIT deadline was still in the future. It is a timeout subtype so
	// callers that only care that a deadline expired still match, but the
	// diagnostics and the user-facing line name the provider as the source.
	ErrModelProviderTimeout = fmt.Errorf("%w: the provider timed out", ErrModelTimeout)
	// ErrModelCancelled means the caller cancelled the request.
	ErrModelCancelled = errors.New("commit: commit model request was cancelled")
)

Errors that classify a failed proposal request. They exist so a caller can tell a model failure from a UI failure without matching error strings; the user-facing text is normalized separately by AbortText.

View Source
var ErrInvalidProposal = errors.New("commit: invalid proposal")

ErrInvalidProposal means the model's output did not satisfy the message contract. The caller may regenerate within a bounded retry policy; it must never execute a proposal that carries this error.

Functions

func AbortText

func AbortText(err error) string

AbortText maps a classified error to the short, non-nested line a UI should show. The original cause remains available to logs and tests through the wrapped error; the human sees one sentence that names the layer that failed.

func DiagnosticText

func DiagnosticText(d ProposalDiagnostics) string

DiagnosticText renders the internal facts in one line. It is for logs and tests, never for the rendered transcript.

func FormatProposal

func FormatProposal(request *Request) string

FormatProposal renders the review block shown before approval.

func FormatResult

func FormatResult(result Result) string

FormatResult renders one verified commit for a transcript notice.

func ScopeNote

func ScopeNote(snapshot *Snapshot) string

ScopeNote explains what the scope does and does not include, without hiding the decision in prose the reviewer cannot verify.

func ValidationText

func ValidationText(err error) string

ValidationText returns the concrete rule that rejected a message, without the sentinel prefix. A caller that asks the human to correct an edit needs the rule, not a second layer of "commit: invalid proposal".

Types

type FileChange

type FileChange struct {
	// Path is the current repository-relative path.
	Path string
	// OrigPath is the source path of a staged rename, or "".
	OrigPath string
	// Index and Worktree are the porcelain status bytes.
	Index byte
	// Worktree is the worktree status byte.
	Worktree byte
	// Untracked marks the "??" record.
	Untracked bool
	// Ignored marks the "!!" record.
	Ignored bool
	// Internal marks ohgo's own project state.
	Internal bool
}

FileChange is one path in the repository state.

func (FileChange) Code

func (c FileChange) Code() string

Code renders the status a reviewer should read for this entry.

func (FileChange) Display

func (c FileChange) Display() string

Display renders one proposal line, e.g. "M agent/loop.go".

func (FileChange) Staged

func (c FileChange) Staged() bool

Staged reports whether this change is in the index.

func (FileChange) Unstaged

func (c FileChange) Unstaged() bool

Unstaged reports whether this change is in the worktree.

type Mode

type Mode string

Mode is how the exact commit scope was selected.

const (
	// ModeStaged commits the existing index only. It is chosen whenever the
	// index already has a change, because replacing a staged version with the
	// worktree version would silently discard the user's staging intent.
	ModeStaged Mode = "staged"
	// ModeWorktree stages every tracked modification and untracked file when
	// the index is clean.
	ModeWorktree Mode = "worktree"
)

type Proposal

type Proposal struct {
	// Type is the conventional-commit type.
	Type string
	// Scope names the area changed.
	Scope string
	// Summary is the subject text after ": ".
	Summary string
	// Body is the optional bullet list, in order.
	Body []string
}

Proposal is the model's untrusted commit text, split into the fields a reviewer needs to see. Body holds complete bullet lines, each starting "- ".

func Parse

func Parse(text string, refs map[string]bool) (Proposal, error)

Parse converts untrusted model text into a Proposal and validates it.

refs is the set of references present in the evidence. A #123 or URL token absent from that set is rejected as invented. The parser accepts an optional single outer code fence because models routinely add one; the message inside it still has to pass every rule.

func (Proposal) Message

func (p Proposal) Message() string

Message returns the exact text passed to Git: subject, one blank line when a body exists, then the bullets. There is no trailing newline.

func (Proposal) Subject

func (p Proposal) Subject() string

Subject returns the complete first line.

func (Proposal) Validate

func (p Proposal) Validate(refs map[string]bool) error

Validate applies every deterministic rule to a proposal.

type ProposalDiagnostics

type ProposalDiagnostics struct {
	// Provider is the resolved provider key, e.g. "openrouter".
	Provider string
	// Model is the resolved model id.
	Model string
	// MaxOutputTokens is the completion budget sent to the provider.
	MaxOutputTokens int
	// PromptBytes is the byte length of the system prompt plus the user
	// evidence message on the final attempt.
	PromptBytes int
	// EvidenceBytes is the byte length of the bounded repository evidence.
	EvidenceBytes int
	// InputTokens, OutputTokens, and ReasoningTokens are provider-reported
	// totals across every attempt in this request. ReasoningTokens stays zero
	// when the provider does not report it separately.
	InputTokens     int
	OutputTokens    int
	ReasoningTokens int
	// Reasoning reports whether an effort was sent. ReasoningEffort is the
	// value sent, including "none" when the provider has an explicit disable.
	Reasoning       bool
	ReasoningEffort string
	// Regenerations is the number of validation-triggered retries.
	Regenerations int
	// RetryReasons records the deterministic rule that rejected each attempt,
	// in order. Rejected model text is never retained.
	RetryReasons []string
	// ProposalValid reports that a validated proposal was produced.
	ProposalValid bool
	// StartedAt is when the proposal request began.
	StartedAt time.Time
	// EndedAt is when it finished, failed, or was cancelled.
	EndedAt time.Time
	// Timeout is the configured request budget.
	Timeout time.Duration
	// Deadline is the effective deadline the request ran under.
	Deadline time.Time
	// ContextDeadline is the caller context's own deadline, if it had one.
	// It is recorded separately because an inherited deadline must never be
	// mistaken for the COMMIT policy's own deadline.
	ContextDeadline time.Time
	// Elapsed is EndedAt minus StartedAt.
	Elapsed time.Duration
	// Attempts is the number of model calls made in this request.
	Attempts int
	// CancellationReason names why the request stopped when it did:
	// "timeout", "user", "session", "superseded", or "cancelled".
	CancellationReason string
	// ProviderStatus is the HTTP status when the provider returned one.
	ProviderStatus int
}

ProposalDiagnostics records the observable facts of one COMMIT request. It is carried by ProposalError and handed to Service.OnDiagnostics, so a timeout can be attributed without parsing rendered text.

func DiagnosticsOf

func DiagnosticsOf(err error) (ProposalDiagnostics, bool)

DiagnosticsOf returns the diagnostics attached to a proposal failure.

type ProposalError

type ProposalError struct {
	// Kind is one of the ErrModel* sentinels.
	Kind error
	// Message is the internal classification sentence.
	Message string
	// Cause is the transport or validation error that triggered it.
	Cause error
	// Diagnostics describes the request that failed.
	Diagnostics ProposalDiagnostics
}

ProposalError classifies one failed proposal request and preserves the provider's original cause alongside the diagnostics.

func (*ProposalError) Error

func (e *ProposalError) Error() string

func (*ProposalError) Unwrap

func (e *ProposalError) Unwrap() []error

Unwrap exposes both the classification and the original cause to errors.Is and errors.As.

type Request

type Request struct {
	// Proposal is the validated commit text.
	Proposal Proposal
	// Snapshot is the exact scope and concurrency guard.
	Snapshot *Snapshot
}

Request is one reviewable proposal plus the frozen state it came from.

type Result

type Result struct {
	// SHA is the commit Git created.
	SHA string
	// Tree is the exact tree the verified index held.
	Tree string
	// Subject is the approved first line.
	Subject string
	// Message is the exact approved message.
	Message string
	// Files is the scope that was committed.
	Files []FileChange
	// Remaining lists non-internal changes still present afterwards.
	Remaining []FileChange
	// Clean reports that `git status` proved no relevant change remains.
	Clean bool
}

Result is the verified outcome of an approved commit.

type Service

type Service struct {
	// Root is the repository working directory.
	Root string
	// Stream opens one completion.
	Stream ai.StreamFn
	// Model is the COMMIT-role model.
	Model ai.Model
	// Effort is the role's thinking effort ("", "off", or a level).
	Effort string
	// MaxTokens bounds the proposal completion.
	MaxTokens int
	// Timeout bounds one proposal request. Zero uses DefaultProposalTimeout.
	Timeout time.Duration
	// OnDiagnostics receives the observable facts of every proposal request,
	// including successful ones. It runs on the request goroutine and must
	// not block the UI.
	OnDiagnostics func(ProposalDiagnostics)
	// MaxAttempts bounds validation retries. Zero uses three.
	MaxAttempts int
	// OnStaged runs after staging and before verification. It exists so a
	// test can inject the race the verifier must refuse; production always
	// leaves it nil.
	OnStaged func()
}

Service proposes and executes commits in one repository.

Stream is the shared provider transport, and Model is resolved from the dedicated COMMIT role by the caller. Neither a tool set nor an agent loop is involved: the model can only return text.

func (*Service) Execute

func (s *Service) Execute(ctx context.Context, request *Request) (Result, error)

Execute commits exactly the approved request, at most once.

func (*Service) Propose

func (s *Service) Propose(ctx context.Context) (request *Request, err error)

Propose inspects the repository and asks the commit model for one validated proposal. It is read-only.

The caller's context owns lifecycle (user cancellation, session shutdown). The bounded COMMIT deadline applies to the model request itself, so a slow local Git inspection is never misreported as a model timeout and the policy is not duplicated in every host.

type Snapshot

type Snapshot struct {
	// Root is the repository checkout root.
	Root string
	// Branch is the checked-out branch, or "" when detached.
	Branch string
	// Head is the commit HEAD pointed at when the proposal was built.
	Head string
	// Mode is how Scope was selected.
	Mode Mode
	// Staged, Unstaged, and Untracked classify every relevant path.
	Staged    []FileChange
	Unstaged  []FileChange
	Untracked []FileChange
	// Ignored and Internal are shown but never committed.
	Ignored  []FileChange
	Internal []FileChange
	// Scope is the exact set of paths the human is approving.
	Scope []FileChange
	// Expected maps every approved path to its expected index or worktree
	// blob hash. A missing key is a staged deletion.
	Expected map[string]string
	// Fingerprint covers HEAD, branch, status codes, and worktree content.
	Fingerprint string
	// WorktreeFingerprint covers HEAD, paths, and worktree content only. It
	// is the comparison after staging, when index codes legitimately moved.
	WorktreeFingerprint string
	// DiffStat and Diff are bounded evidence.
	DiffStat string
	Diff     string
	// Refs is every issue/PR/URL token present in the evidence.
	Refs map[string]bool
	// contains filtered or unexported fields
}

Snapshot is the exact repository state a proposal was built from.

It is also the concurrency guard: Fingerprint and WorktreeFingerprint must still match immediately before execution, or the commit is aborted rather than silently absorbing a change nobody approved.

func BuildSnapshot

func BuildSnapshot(ctx context.Context, repo *vcs.RepoInfo) (*Snapshot, error)

BuildSnapshot inspects the repository and freezes the candidate scope.

It is read-only: status, log, diff, and hash-object only. Nothing is staged and no ref moves.

func (*Snapshot) Evidence

func (s *Snapshot) Evidence() string

Evidence renders the bounded repository evidence for the prompt.

func (*Snapshot) ExpectedStagedPaths

func (s *Snapshot) ExpectedStagedPaths() []string

ExpectedStagedPaths is the index path set the approved commit must have.

A staged rename contributes both its new path and its old path: with rename detection disabled, the staged diff names the deletion and the addition.

func (*Snapshot) StagePaths

func (s *Snapshot) StagePaths() []string

StagePaths is the explicit path list passed to `git add`, never a wildcard.

func (*Snapshot) SuggestedScope

func (s *Snapshot) SuggestedScope() string

SuggestedScope derives a conventional-commit scope from the approved paths.

It is used only when the model omitted the scope entirely. The most common top-level directory wins; a repository with only root-level changes uses a sanitized repository name, and "repo" is the final honest fallback. A name too long to leave room for a summary is skipped for the same fallback. The value is deterministic for one snapshot, so two identical proposals cannot disagree.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL