Documentation
¶
Overview ¶
Package aicommit implements `gk commit` — WIP clustering into semantic file groups, Conventional Commit message generation via an external AI CLI provider, and safe multi-commit application.
Index ¶
- Constants
- Variables
- func Classify(ctx context.Context, p provider.Provider, files []FileChange, ...) (provider.ClassifyResult, error)
- func CompileWIPPatterns(custom []string) ([]*regexp.Regexp, error)
- func CountHeuristicGroups(groups []provider.Group, lang string) int
- func DetectBinary(path string) (bool, error)
- func DetectWIPChain(ctx context.Context, runner git.Runner, opts DetectWIPChainOptions) ([]WIPCommit, StopReason, error)
- func EnsureBackupRef(ctx context.Context, runner git.Runner) (string, error)
- func EstimateClassifyTokens(files []FileChange) int
- func EstimateComposeTokens(g provider.Group, diff string, lang string) int
- func FileKind(path string) string
- func FilterDiffByDeny(diff string, denyGlobs []string) (string, []string)
- func IsWIPSubject(subject string, patterns []*regexp.Regexp) bool
- func MatchDeny(path string, patterns []string) string
- func PairRustModuleGroups(groups []provider.Group, files []FileChange, unifiedDiff string) []provider.Group
- func PairTestProdGroups(groups []provider.Group) []provider.Group
- func Preflight(ctx context.Context, in PreflightInput) error
- func TruncateDiff(unifiedDiff string, capBytes int) string
- type AbortResult
- type ApplyOptions
- type ApplyResult
- type AuditEntry
- type AuditWriter
- type ClassifyOptions
- type ComposeOptions
- type DetectWIPChainOptions
- type FileChange
- type FileStat
- type GatherOptions
- type Gitleaks
- type Message
- type PreflightInput
- type PrivacyGateOptions
- type RedactFinding
- type ReviewDecision
- type ReviewOptions
- type ReviewPrompter
- type Scope
- type SecretFinding
- type SecretGateOptions
- type StopReason
- type WIPCommit
Constants ¶
const DefaultComposeConcurrency = 4
DefaultComposeConcurrency caps how many groups Compose runs in parallel. Compose is the dominant latency in `gk commit`: each group is an independent LLM round-trip (plus up to MaxAttempts-1 commitlint retries), and running them serially made wall-clock scale linearly with the group count. The groups share no state, so they fan out.
4 is a deliberate ceiling, not a target: it keeps a typical 2-4 group commit fully concurrent while bounding (a) burst pressure on remote providers' rate limits (Groq's free tier in particular) and (b) the number of CLI-provider subprocesses (gemini/qwen/kiro) spawned at once. ai.commit.concurrency overrides it; this is the fallback.
Exported so the CLI can label the effective dispatch ("parallel ×N") without re-deriving the fallback.
const DefaultComposeDiffByteCap = 32 * 1024
DefaultComposeDiffByteCap is the per-group diff size we hand to Provider.Compose. ~32KB ≈ 8K tokens, well under the per-call ceiling for every supported model (Groq llama-3.3-70b allows 8K input tokens per request on the free tier, where this limit was set).
Why bytes, not tokens: cheap to compute and within an order of magnitude of the actual token count. We don't need an exact bound — we need to stop a single 200KB lockfile diff from eating the daily quota.
const DefaultComposePerFileDiffCap = 12 * 1024
DefaultComposePerFileDiffCap is the per-file diff size above which a single file's patch is replaced by a one-line semantic digest (changed symbols, ±lines, hunk count) instead of its raw hunks.
A handful of large files — generated code, big mechanical refactors, vendored blobs — would otherwise dominate the compose payload while adding little the model needs to write a subject. The digest still answers "what changed, where" at a fraction of the tokens. ~12KB ≈ 3K tokens: comfortably above an ordinary hand-edit, below the noise floor where digesting would start dropping detail the composer can use.
const WIPCommitType = "WIP"
WIPCommitType is the Conventional-Commit type used for checkpoint commits created by `gk commit --wip`. It is deliberately the bare "WIP" spelling that DetectWIPChain's baked-in `^[Ww][Ii][Pp]\b` pattern matches, so a later plain `gk commit` folds the whole checkpoint chain into real commits. That round trip is the entire point of the mode: cheap saves now, one semantic history later.
Variables ¶
var ( ErrAIDisabled = errors.New("aicommit: AI feature disabled") ErrRemoteNotAllowed = errors.New("aicommit: remote provider disallowed by policy") ErrGitStateNotNone = errors.New("aicommit: git is in the middle of another operation") ErrGPGKeyMissing = errors.New("aicommit: commit.gpgsign is on but no signing key is available") )
Sentinel errors — callers branch on these via errors.Is.
var ErrReviewAborted = errors.New("review aborted by user")
ErrReviewAborted is returned when the user bails out of the review (ctrl-C in huh, or an explicit "abort" pick).
Functions ¶
func Classify ¶
func Classify( ctx context.Context, p provider.Provider, files []FileChange, opts ClassifyOptions, ) (provider.ClassifyResult, error)
Classify groups the WIP file list into proposed commits.
Hybrid strategy:
- Always compute the heuristic classification.
- If HeuristicOnly OR the file set is small+homogeneous, return it.
- Otherwise call provider.Classify and apply the **path-rule override** so test/docs/ci files always keep their heuristic type even if the LLM picked something else — this is the pitfall research's P2.1 mitigation.
The returned ClassifyResult carries the provider's Model and TokensUsed so the caller can report classify cost; the heuristic short-circuits report Model "heuristic" with zero tokens (no provider call was made).
func CompileWIPPatterns ¶
CompileWIPPatterns merges the baked-in defaults with the caller's custom list and returns compiled regexes. Caller patterns ADD to the defaults; they don't replace — so users can extend without losing well-known cases like git-stash's `--wip--`.
func CountHeuristicGroups ¶
CountHeuristicGroups returns how many of the given groups will be composed without an LLM round-trip. The CLI uses it to surface "X of Y messages composed without LLM" in the status line so users understand where the token savings come from.
func DetectBinary ¶
DetectBinary reports whether the file at path is likely binary.
The check reads up to 8 KiB and reports true when:
- the sample contains a NUL byte, or
- more than 1 in 32 bytes fall outside the printable ASCII + common whitespace range (classic heuristic, same as `git diff`'s default).
Returns false (and no error) when the file is missing — callers that care distinguish via os.Stat. IO errors surface up; they usually mean permission trouble worth reporting rather than papering over.
func DetectWIPChain ¶
func DetectWIPChain(ctx context.Context, runner git.Runner, opts DetectWIPChainOptions) ([]WIPCommit, StopReason, error)
DetectWIPChain walks HEAD backward as long as each commit's subject matches a WIP pattern, returning the chain in HEAD-first order (chain[0] is HEAD, chain[N-1] is the oldest WIP) along with a StopReason explaining why the walk ended.
Safety stops (each maps to a StopReason; chain is whatever was successfully collected up to that point):
- Detached HEAD (`rev-parse --abbrev-ref HEAD` returns "HEAD") → return (nil, StopReasonDetachedHEAD). detached-HEAD reset rewinds the pointer with no branch to recover from.
- Commit reachable from any remote tracking branch → stop. Uses `git branch -r --contains <sha>` rather than relying on `@{upstream}` so manually-pushed commits (`git push origin HEAD` without `-u`) are still caught. Bypass with AllowPushed.
- Merge commit → stop (multi-parent unwrap is risky).
- MaxChain reached → stop, take what we have.
- Root commit → include it (diff-tree --root handles file list) but stop walking (no parent left).
- First commit that doesn't match a WIP pattern → stop. This is the normal terminator and the most common StopReason.
Note: protected branch names are NOT a stop condition here. The per-commit push gate is sufficient — branch-name guarding caused the entire feature to refuse silently on `develop`/`main` even when every WIP commit was purely local. Callers that need extra restraint can set AllowPushed=false (the default) which already keeps pushed history untouched.
Any unexpected git error returns (chain-so-far, "", err) — the caller should treat that as "skip the unwrap step" rather than aborting commit.
func EnsureBackupRef ¶
EnsureBackupRef creates a refs/gk/ai-commit-backup/<branch>/<unix> ref pointing at HEAD and returns its full path. Safe on detached HEAD — BackupRefName renders the segment as "detached". Returns the ref path even when HEAD is unborn (no commits yet); in that case no ref is actually created and callers get an empty string.
func EstimateClassifyTokens ¶
func EstimateClassifyTokens(files []FileChange) int
EstimateClassifyTokens approximates the input token count of a single Provider.Classify request. Classify only sees the file list (no diff content), so it's very cheap — ~500 tokens for a 60-file repo. Surfaced in --dry-run for completeness.
func EstimateComposeTokens ¶
EstimateComposeTokens approximates the input token count of a single Provider.Compose request for the given group/diff. Returns 0 for groups that the heuristic bypass will short-circuit (lockfile-only build groups, CI-only groups), since those never reach the LLM.
Use this in `--dry-run` to surface per-group cost before any API call. The number is upper-bounded by the diff already having been truncated via TruncateDiff (DefaultComposeDiffByteCap).
func FileKind ¶
FileKind classifies a path into the coarse change category used by surfaces like `gk diff --digest` (test / docs / ci / build); empty when the path is regular source. Exported wrapper over the commit classifier's path heuristics so the vocabulary stays in one place.
func FilterDiffByDeny ¶
FilterDiffByDeny removes per-file blocks whose path matches any deny glob from a unified git diff, returning the filtered diff and the dropped paths. Any prefix before the first "diff --git" marker (commit headers from `git show`/`git log -p`) is preserved. Input without git diff markers passes through unchanged — callers must not treat that as "filtered".
This exists because deny_paths historically applied only to the working-tree file list: `git show <old-sha>` or `git log -p` would happily print a denied file's HISTORIC content, bypassing the gate entirely (gk chat cross-vendor research, Critical finding). Structural removal of whole file blocks is the defense; line-level secret regexes are the fallback, not the primary.
func IsWIPSubject ¶
IsWIPSubject returns true when subject matches any compiled pattern.
Subjects are first stripped of a leading noise prefix (runs of backticks and whitespace) before matching. Past LLM runs occasionally leaked fenced-code-block markers into the subject line — without this normalization a polluted subject like "``` WIP(...)" would slip past the WIP-anchored patterns and break chain unwrap.
func MatchDeny ¶
matchDeny returns the first glob in patterns that matches path. Empty result means no match.
Matching strategy (each pattern tried in order until one hits):
- basename match — covers bare globs like "*.pem", ".env"
- full-path match — covers explicit prefixes like ".aws/credentials"
- component-wise match — covers "any depth" patterns like "__pycache__" or "__pycache__/*", which filepath.Match cannot express. Matches when the pattern (or its first segment) hits any path component.
Why (3) exists: filepath.Match has no doublestar; "__pycache__/*" against "internal/foo/__pycache__/bar.pyc" fails. Without component scanning, every nested cache directory leaks into the LLM payload. MatchDeny reports the first deny glob matching a repo-relative, slash-separated path (empty = no match). Exported for the chat tool sandbox, which must apply the exact same deny semantics to model-driven file access that this package applies to commit diffs — two divergent matchers would eventually disagree on what ".env" means.
func PairRustModuleGroups ¶
func PairRustModuleGroups(groups []provider.Group, files []FileChange, unifiedDiff string) []provider.Group
PairRustModuleGroups keeps an added Rust module source file in the same commit group as the added declaration that requires it. Without this, a generated multi-commit history can contain an intermediate `pub mod x;` commit that cannot compile because x.rs lands later.
Only explicit added declarations and added/untracked candidate files move. Existing files and unrelated sibling edits remain under the classifier's decision. The diff must describe the same change set as files.
func PairTestProdGroups ¶
PairTestProdGroups merges Go test files into their production-file group when the heuristic (or LLM) parked them in a separate "test" group. Returns the input slice with empty groups dropped.
Why: heuristicGroups buckets files purely on heuristicType — so `switch.go` (type "chore") and `switch_test.go` (type "test") always split, even when co-changed. The LLM Classify path can also miss the pairing when the prod file lacks strong type signal. Merging here lets one Compose call see both diffs and emit one cohesive message; it also stops --dry-run from showing the worst-case split.
Scope deliberately conservative (debate verdict — Option A):
- Go only: `foo_test.go` ↔ `foo.go`. TS/Py/Rust skipped — basename ambiguity (`.ts`/`.tsx`, `test_foo.py` vs `tests/foo_test.py`, in-file `#[cfg(test)]`) costs more in maintenance than it gains.
- Pair only when the production counterpart sits in the same changeset. Orphan tests (integration_test.go, helpers_test.go, or foo_test.go with no foo.go in the diff) stay in the test group as before.
- The merged group inherits the production group's Type/Scope — no chore → feat promotion. Compose still sees the original label; it just gets richer diff context.
func Preflight ¶
func Preflight(ctx context.Context, in PreflightInput) error
Preflight blocks the run when any safety / policy condition fails:
- AI feature disabled (config or GK_AI_DISABLE=1) → ErrAIDisabled.
- Remote provider when AllowRemote is false → ErrRemoteNotAllowed.
- In-progress git op (rebase/merge/cherry-pick/revert/bisect) → ErrGitStateNotNone.
- commit.gpgsign=true but no signing key available → ErrGPGKeyMissing.
- Provider.Available() non-nil → wrapped.
Every error is a sentinel (or wraps one) so the CLI can switch on errors.Is and print a tailored hint.
func TruncateDiff ¶
TruncateDiff trims a unified diff so its length stays under capBytes while preserving file boundaries. Per-file output is one of:
- a one-line semantic digest (changed symbols, ±lines, hunk count) when the file's own diff exceeds DefaultComposePerFileDiffCap, or when its raw hunks won't fit the remaining group budget
- the full file diff otherwise
The function never splits inside a hunk — partial hunks confuse the LLM and produce nonsense subjects. capBytes <= 0 disables the cap (and per-file digesting) and returns the input unchanged.
Digesting an oversized file instead of byte-truncating it keeps the signal the composer actually uses — which functions changed — at a tiny, predictable token cost, where the old behaviour emitted an opaque "[N bytes truncated]" stub the model could not reason about.
Types ¶
type AbortResult ¶
type AbortResult struct {
// SafetyRef is the backup ref written at the pre-abort HEAD — this
// abort's own undo point. Empty when backupRef was empty (no-op) or the
// ref write failed (best-effort; never blocks the abort itself).
SafetyRef string
// StashConflict is set only when the tree carried tracked-file changes
// and the autostash pop after the reset could not reapply cleanly (e.g.
// a conflict) — the caller should tell the user to finish manually via
// `git stash pop`. Empty on the common path (clean tree, or pop
// succeeded).
StashConflict string
}
AbortResult is returned by AbortRestore.
func AbortRestore ¶
AbortRestore resets HEAD back to the given backup ref while preserving the working tree. An abort means "uncommit so I can regroup/reword", not "discard the work": StrategyMixed moves HEAD and resets the index, leaving both successful AI commits and any later edits as unstaged changes.
Before resetting, a safety-net ref is also written at the CURRENT HEAD (refs/gk/ai-commit-abort-backup/<branch>/<unix>, pruned the same conservative way as the run-start backup) so the caller can tell the user where their aborted state went.
Empty backupRef is a no-op returning (AbortResult{}, nil) — callers should branch on that case to print a friendly "nothing to abort" message.
type ApplyOptions ¶
type ApplyOptions struct {
Trailer string
DryRun bool
SkipGpgKeyCheck bool
// PrecapturedBackupRef, when non-empty, replaces the backup ref
// that ApplyMessages would otherwise create at entry. Callers that
// rewrite history before calling Apply (e.g. WIP chain unwrap) use
// this so the recorded backup points at the ORIGINAL pre-rewrite
// HEAD rather than the post-rewrite ancestor.
PrecapturedBackupRef string
}
ApplyOptions configures ApplyMessages.
Trailer, when non-empty, is appended as "Trailer: <value>" to each commit (provider + model attribution — opt-in via ai.commit.trailer). DryRun prints the plan to stdout but skips `git add`/`commit`. SkipGpgKeyCheck is a test hook; real runs should keep false.
type ApplyResult ¶
ApplyResult is what the caller receives after ApplyMessages runs. CommitShas[i] corresponds to Messages[i]; an empty entry means that group failed (DryRun also leaves entries empty).
func ApplyMessages ¶
func ApplyMessages(ctx context.Context, runner git.Runner, messages []Message, opts ApplyOptions) (ApplyResult, error)
ApplyMessages creates one commit per Message. Files from each group are staged with `git add -A -- <files>` — `-A` so unstaged deletions and renames stage alongside additions/modifications (plain `git add` skips removed paths and fails with "pathspec did not match any files"); the trailing `--` keeps filenames starting with `-` from being misread.
Files whose deletion is already fully staged (porcelain "D ": gone from working tree AND from index, only present in HEAD) are excluded from the `git add` invocation — `git add -A` on them still fails the pathspec check because nothing matches. The follow-up `git commit -- <files>` picks the deletion up via the staged HEAD diff.
Rename pair expansion in commit pathspec: staged rename pairs (new→orig) are recomputed for each group (a prior group's commit can change what is staged). For each group the commit pathspec is expanded via expandRenamePairs so that the orig (deletion) side is included alongside the new path — preventing dangling staged deletions when the grouper only emits the new path. Fully-staged deletions are likewise recomputed per group so a deletion committed by group i doesn't make group i+1's `git add -A` fail the pathspec check on a path that is no longer in the index.
Tree-OID guard: ApplyMessages records `git write-tree` before any commit and again after all commits. A mismatch between TreeBefore and the ORIGINAL tree (captured upstream) signals drift between classification and application — callers should compare before they call ApplyMessages, but TreeBefore is returned for the audit trail.
On the first error the function returns the partial result (commits already made remain in history; caller can use BackupRef + `gk commit --abort` to restore).
type AuditEntry ¶
type AuditEntry struct {
TS time.Time `json:"ts"`
RunID string `json:"run_id"`
Provider string `json:"provider"`
Model string `json:"model,omitempty"`
CommitSha string `json:"commit_sha,omitempty"`
GroupType string `json:"group_type"`
GroupScope string `json:"group_scope,omitempty"`
Files []string `json:"files"`
Subject string `json:"subject"`
Tokens int `json:"tokens,omitempty"`
Attempts int `json:"attempts,omitempty"`
DryRun bool `json:"dry_run,omitempty"`
BackupRef string `json:"backup_ref,omitempty"`
}
AuditEntry is one line in .git/gk-ai-commit/audit.jsonl.
The file is append-only; a new entry is written per applied commit (so a 3-group run produces 3 entries sharing a RunID). Consumers can group by RunID to reconstruct a single `gk commit` execution.
type AuditWriter ¶
type AuditWriter struct {
// contains filtered or unexported fields
}
AuditWriter opens (or creates) the audit jsonl inside the repo's .git dir. Closing is the caller's responsibility.
The file lives in .git/gk-ai-commit/audit.jsonl so it is not committed. Rotation is the user's problem for v1 — we only append.
func OpenAuditLog ¶
func OpenAuditLog(gitDir string) (*AuditWriter, error)
OpenAuditLog returns an AuditWriter writing into gitDir, which is normally the output of `git rev-parse --git-dir`. Creates any missing directories.
func (*AuditWriter) Close ¶
func (a *AuditWriter) Close() error
Close flushes and closes the underlying file.
func (*AuditWriter) Write ¶
func (a *AuditWriter) Write(entry AuditEntry) error
Write serializes entry as one JSON line, terminated by '\n'.
type ClassifyOptions ¶
type ClassifyOptions struct {
HeuristicOnly bool
// HybridFileLimit: when len(files) <= this AND all files share a
// single top-level directory, the heuristic alone decides. Default 5.
HybridFileLimit int
AllowedTypes []string
AllowedScopes []string
Lang string
// ScopeRequired mirrors commit.scope_required. Heuristic groups carry
// no scope, so when a scope is mandatory the definite-kind fast path is
// disabled: a scopeless heuristic message would fail commitlint, so the
// LLM Classify path runs instead (it can infer a scope).
ScopeRequired bool
}
ClassifyOptions shapes Classify behaviour.
HeuristicOnly forces the path-based heuristic and skips the LLM entirely (useful for --no-llm / tests). Threshold configures when the hybrid strategy falls back to the LLM. AllowedTypes constrains both the heuristic and the LLM to valid Conventional Commit types.
type ComposeOptions ¶
type ComposeOptions struct {
MaxAttempts int
AllowedTypes []string
ScopeRequired bool
MaxSubjectLength int
Lang string
// Concurrency caps how many groups Compose runs in parallel. <= 0
// falls back to defaultComposeConcurrency. Wired from
// ai.commit.concurrency so operators can tighten it for strict
// provider rate limits or loosen it on a paid tier.
Concurrency int
// WarmCache, when true and there is more than one LLM group, runs the
// first group synchronously before fanning out the rest. The first
// call populates the provider's prompt cache (Anthropic's ephemeral
// system-prompt cache) so the parallel siblings read the cached prefix
// instead of each paying a cache-miss. Pure latency plays leave this
// false; the CLI sets it only for cache-capable providers.
WarmCache bool
}
ComposeOptions tunes the retry loop.
MaxAttempts is the total number of Compose calls per group (1 initial + up to MaxAttempts-1 retries). 3 is a good default; 0 falls back to 3. AllowedTypes and MaxSubjectLength mirror the repo's commitlint rules and are forwarded to the provider.
type DetectWIPChainOptions ¶
type DetectWIPChainOptions struct {
// MaxChain caps how many commits we'll consider unwrapping. 0
// falls back to defaultMaxChain (10). Prevents runaway when a
// user's branch is entirely save-point commits.
MaxChain int
// Patterns is the compiled regex list. Use CompileWIPPatterns to
// build, which already merges defaults + custom.
Patterns []*regexp.Regexp
// AllowPushed disables the per-commit `branch -r --contains` gate
// that stops the walk at the first commit already on a remote. Set
// by `gk commit --force-wip` when the user explicitly accepts that
// unwrapping will rewrite already-pushed history (force-push
// required afterward).
AllowPushed bool
}
DetectWIPChainOptions tunes DetectWIPChain.
type FileChange ¶
type FileChange struct {
Path string
Status string
// Added and Deleted are the exact line deltas when the caller has a
// diff digest available. They let classification distinguish a small
// signature adjustment from the feature that dominates the change.
// Zero values mean the caller could not compute a text diff (for example
// a binary file), not that the file is unchanged.
Added int
Deleted int
Staged bool
Unstaged bool
IsBinary bool
// OrigPath is set for renames/copies — the source side.
OrigPath string
// DeniedBy is non-empty when the path matched a DenyPaths glob;
// matched files are kept in the slice so callers can warn, but
// must never be forwarded to the provider.
DeniedBy string
}
FileChange is one file in the working tree worth committing.
Status is normalised to one of:
"added" — new in the index (A_ or _A in porcelain v2) "modified" — content changed (M_, _M, MM, AM, etc.) "deleted" — removed (D_, _D) "renamed" — rename-detected (R_) "copied" — copy-detected (C_) "untracked" — `?` entry (no index side) "unmerged" — conflicted (`u` record in porcelain v2)
Staged is true when the index differs from HEAD for this path; Unstaged is true when the worktree differs from the index. Both can be true (staged + further edits). Untracked is true for `?` entries and always implies !Staged && !Unstaged.
IsBinary is a best-effort flag derived from `.gitattributes` (`binary`, `-diff`) and fallback content sniffing for the first 8KiB of the worktree file. Binary files are forwarded to the provider as stats-only stubs.
func ChainNetFiles ¶
ChainNetFiles returns the files that actually differ between the chain's base (HEAD~chainLen) and HEAD — the net diff the unwrap (`git reset HEAD~N`, mixed) will leave in the working tree.
This replaced MergeChainFiles, a pure per-commit-status simulation: the simulation tracked add→delete cancellation but could not see CONTENT cancellation — a later WIP reverting an earlier WIP's edit still listed the path, the AI planned a commit for it, and apply died on `git commit -- <path>` finding a clean tree after the reset ("nothing to commit, working tree clean"). Asking git for the real HEAD~N→HEAD diff makes both cancellation kinds fall out for free, renames included.
func GatherWIP ¶
func GatherWIP(ctx context.Context, runner git.Runner, opts GatherOptions) ([]FileChange, error)
GatherWIP runs `git status --porcelain=v2 -z --untracked-files=all` and returns the normalised list of FileChange entries.
DeniedBy is populated for paths matching any DenyPaths glob; those entries are still returned so callers can warn, but must never be forwarded to a provider.
type FileStat ¶
type FileStat struct {
// Glyph is the single-char change kind (M/A/D/R/C/T). Empty defaults
// to "M" at render time.
Glyph string
Added int
Deleted int
// Symbols is the pre-joined "fn, fn2, +N more" display string; empty
// when the file has no informative symbols (or is docs/build).
Symbols string
}
FileStat is display-ready per-file change info for the plan preview, mirroring one row of `gk diff --digest`. All fields are presentation values the caller already computed (glyph mapped, symbols joined and truncated, docs/build symbols suppressed); printSummary only lays them out.
type GatherOptions ¶
GatherOptions controls GatherWIP.
type Gitleaks ¶
type Gitleaks interface {
Run(ctx context.Context) ([]scan.GitleaksFinding, error)
}
Gitleaks lets tests inject a fake runner. When nil the payload is scanned with the gitleaks ruleset embedded in gk, or with the gitleaks binary when the repo has a gitleaks config (see defaultGitleaks).
type Message ¶
type Message struct {
Group provider.Group
Subject string
Body string
// Breaking, when true, appends the Conventional Commits "!" marker to
// the header (e.g. "feat(x)!: ..."). Set by plan-driven commits whose
// message carried a "!" or a "BREAKING CHANGE" footer; the AI path
// leaves it false (the model encodes breaking changes in the footer
// instead).
Breaking bool
// AllowEmpty permits a commit with no files via `git commit
// --allow-empty`. Only honoured when Group.Files is empty; ApplyMessages
// otherwise stages and commits the listed pathspecs as usual.
AllowEmpty bool
// Attempts is the number of Provider.Compose calls it took to
// produce a commitlint-clean message. 1 is the happy path;
// values >1 indicate the retry loop fired.
Attempts int
// Model records the provider's concrete model id (when available).
Model string
}
Message is one fully-formed commit message draft along with the Group it targets. Subject/Body come from Provider.Compose after commitlint validation; Footers may be empty.
func ComposeAll ¶
func ComposeAll( ctx context.Context, p provider.Provider, groups []provider.Group, diffs map[string]string, opts ComposeOptions, ) ([]Message, error)
ComposeAll runs Provider.Compose per group with commitlint validation after each attempt. Groups are independent, so they are composed CONCURRENTLY (bounded by defaultComposeConcurrency) and the results re-assembled in input order — out[i] always corresponds to groups[i].
On unrecoverable failure for a single group the call returns (nil, err): the first failing group's error is surfaced and the shared context is cancelled so in-flight siblings stop early. That lets the caller distinguish "partial success" (all N messages returned) from "outright failure". Partial-success scenarios for mixed retries are not supported yet — if the user wants that, they can drop the offending group and re-run.
func FallbackWIPMessage ¶
func FallbackWIPMessage(files []FileChange, scope string) Message
FallbackWIPMessage builds the checkpoint commit used when the AI path is unavailable — no provider configured, preflight failed, or compose errored out. It carries no summary beyond the file count because there is nothing trustworthy to summarise with.
The contract this exists to uphold: `gk commit --wip` NEVER loses work to a provider outage. An automated checkpoint that refuses to commit because a model was down is strictly worse than one with a dull message.
func MarkAsWIP ¶
MarkAsWIP rewrites composed messages so their header reads "WIP(scope): <summary>" instead of "feat(scope): <summary>".
Why rewrite instead of asking the model for a WIP header directly: Compose runs the full commitlint retry loop against the configured type list, which does not (and should not) contain "WIP". Letting the model produce a normal Conventional Commit and swapping the type afterwards keeps the prompt, the validation, and every provider adapter untouched — the checkpoint mode is a post-processing step, not a second prompt dialect.
The subject is stripped of its original "<type>(<scope>): " prefix first. Header() strips only a prefix matching the CURRENT type, so without this a subject the model spelled out in full would surface twice: "WIP(remote): feat(remote): add the thing".
func (Message) Header ¶
Header returns the Conventional-Commits header line, "<type>(<scope>): <subject>". Any leading prefix the LLM duplicated onto Subject is stripped so the line never doubles up to "build: build: ...". This is the single source of truth for rendering a message's header — formatCommitMessage (the committed message), the plan summary, and the interactive picker all route through it, so the preview always matches what actually gets committed.
type PreflightInput ¶
type PreflightInput struct {
Runner git.Runner
WorkDir string
AI config.AIConfig
Provider provider.Provider
EnvLookup func(string) string // defaults to os.Getenv
SkipGPGKey bool // test hook
AllowRemote bool // cfg.AI.Commit.AllowRemote, copied here for clarity
}
PreflightInput collects everything Preflight needs. Callers inject Runner so tests can fake git state.
type PrivacyGateOptions ¶
type PrivacyGateOptions struct {
DenyPaths []string // glob patterns (filepath.Match syntax)
SecretPatterns []*regexp.Regexp // extra patterns beyond built-in
AuditEnabled bool
AuditPath string // ".gk/ai-audit.jsonl"
MaxSecrets int // default: 10, abort threshold (use -1 to disable)
}
PrivacyGateOptions configures the Redact function.
type RedactFinding ¶
type RedactFinding struct {
Kind string `json:"kind"` // "secret" | "path" | "pii"
Original string `json:"original"` // masked sample (first 4 chars + "***")
Placeholder string `json:"placeholder"` // "[SECRET_1]", "[PATH_1]"
Line int `json:"line"` // line within the redacted payload
File string `json:"file,omitempty"` // resolved source file (may be "")
FileLine int `json:"file_line,omitempty"` // 1-based line within File
Pattern string `json:"pattern,omitempty"` // regex/source that matched
// Untallied marks a finding that was redacted but deliberately left out
// of the abort threshold: a documented example value, an obvious
// placeholder, or a repeat of a value already counted. Reason names which.
// The finding is still reported and still redacted — this only records
// that it did not spend threshold budget.
Untallied bool `json:"untallied,omitempty"`
Reason string `json:"reason,omitempty"` // "placeholder" | "duplicate"
}
RedactFinding records one redaction event.
Line is the 1-based line number within the full payload (the blob the gate scanned). When the payload is the `secrets.PayloadFileHeader(<path>)\n<contents>` shape produced by summariseForSecretScan, File and FileLine resolve back to the source file and its in-file line so error reporting can point the user at the original location.
func Redact ¶
func Redact(payload string, opts PrivacyGateOptions) (string, []RedactFinding, error)
Redact scans payload for deny_paths matches and secret patterns, replacing each with a numbered placeholder. Returns the redacted payload, a slice of findings, and an error if the secret count exceeds MaxSecrets.
Every match is redacted, including the ones exempted from the threshold: the gate's job is to keep raw values out of a remote provider's payload, and the placeholder heuristic reads the whole line, so it is deliberately broader than "definitely not a credential". Redacting a documented example key costs nothing; forwarding a real one that happened to sit next to the word "example" does not.
When the threshold is exceeded, the returned findings slice is still populated so callers can render a detailed report. Set MaxSecrets to a negative value to disable the abort while keeping redaction.
type ReviewDecision ¶
type ReviewDecision struct {
// Keep is true when the group should be applied as shown.
Keep bool
// Drop is true when the user chose to skip this group.
Drop bool
// Regenerate is true when the user asked for a retry; callers re-run
// Compose on this single group with a fresh retry counter.
Regenerate bool
// EditedSubject / EditedBody capture in-place edits. When both are
// empty the original message is kept.
EditedSubject string
EditedBody string
}
ReviewDecision is the per-group action a user picked in ReviewPlan.
func ReviewPlan ¶
func ReviewPlan(messages []Message, opts ReviewOptions) ([]ReviewDecision, error)
ReviewPlan prints a summary of all proposed commits, then asks the user for a per-group decision. The returned slice lines up 1:1 with messages; callers filter on Decision.Keep to build the final apply list.
type ReviewOptions ¶
type ReviewOptions struct {
Out io.Writer
Force bool
NonInteractive bool
// Prompter is an optional hook for tests — when nil ReviewPlan
// falls back to ui.Confirm for accept/drop prompts.
Prompter ReviewPrompter
// FileStats maps a changed path to its display-ready change stats.
// When non-nil, printSummary annotates each file with its change
// kind + line delta and prints a totals line; nil keeps the plain
// "• path" preview (plan-run / tests / a digest that failed to
// build). aicommit never parses a diff itself — the CLI builds this.
FileStats map[string]FileStat
}
ReviewOptions shapes ReviewPlan rendering + behaviour.
Out is where the summary is written (stdout by default). Force short-circuits review: every group's Decision comes back Keep=true without prompting. NonInteractive is for CI: when true and Force is false the function returns ErrNonInteractive immediately so callers can require --yes/--force on non-TTY sessions.
type ReviewPrompter ¶
type ReviewPrompter interface {
Prompt(index, total int, m Message) (ReviewDecision, error)
}
ReviewPrompter abstracts the per-message accept/regenerate/drop prompt so tests can inject decisions without spawning huh.
type SecretFinding ¶
type SecretFinding struct {
Source string
Kind string
File string
Line int
Sample string // masked / truncated; never raw secret
}
SecretFinding is one hit from the secret gate. Source names which scanner produced it ("builtin" or "gitleaks") so callers can phrase advice ("install gitleaks for deeper coverage") accurately.
func ScanPayload ¶
func ScanPayload(ctx context.Context, payload string, opts SecretGateOptions, gl Gitleaks) ([]SecretFinding, error)
ScanPayload runs both scanners over the supplied text (usually the aggregated diff) and returns deduplicated SecretFindings. An injected Gitleaks reporting ErrGitleaksNotInstalled is skipped silently — the built-in scanner is always the baseline.
type SecretGateOptions ¶
type SecretGateOptions struct {
ExtraPatterns []*regexp.Regexp
AllowKinds []string
RunGitleaks bool
RepoDir string
}
SecretGateOptions configures the gate.
ExtraPatterns adds repo-configured regexes to the built-in scanner (matches internal/secrets.Scan's second arg). AllowKinds suppresses findings whose Kind matches — used by `--allow-secret-kind` on the CLI. RunGitleaks gates the second scan with the gitleaks ruleset; default true. RepoDir is the repo root, where a gitleaks config is looked up; payload paths are relative to it.
type StopReason ¶
type StopReason string
StopReason is the *why* attached to the end of a DetectWIPChain walk. It is reported regardless of whether the returned chain is empty or non-empty, so the CLI can explain "we found 2 then stopped at a pushed commit" or "we found nothing because HEAD isn't WIP".
const ( StopReasonNone StopReason = "" // shouldn't happen in practice — kept for zero value StopReasonNonWIPSubject StopReason = "non-wip" // hit a normal commit (usual stop condition) StopReasonDetachedHEAD StopReason = "detached-head" // refused outright; no branch to recover from StopReasonPushed StopReason = "pushed" // hit a commit already on a remote StopReasonMergeCommit StopReason = "merge-commit" // multi-parent — unwrap is risky StopReasonRootCommit StopReason = "root-commit" // reached repo root (parentless WIP) StopReasonMaxChain StopReason = "max-chain" // walked MaxChain entries and they were all WIP StopReasonShallowHistory StopReason = "shallow" // HEAD~i missing (shallow clone, etc.) )
type WIPCommit ¶
type WIPCommit struct {
SHA string
Subject string
Files []FileChange
}
WIPCommit is one entry in the detected unwrap chain.