Imported from JuniaWonter/gi-ai-commit (
AGENTS.md). Install upstream withnpx skills add JuniaWonter/gi-ai-commit. Copyright stays with the author.
AGENTS.md
Commands
make build # go build -o git-ai
make test # go test ./...
make lint # go vet ./...
make fmt # go fmt ./...
make deps # go mod tidy && go mod download
# Single package test
go test ./internal/diff/...
go test -v ./internal/diff/ -run TestParseNumStat
Architecture
Flow: main.go → cmd/commit.go (orchestration) → tui/commit_flow.go (bubbletea TUI)
Key directories:
cmd/- Commit flow orchestration (git checks, config, AI init, TUI launch)tui/- bubbletea UI: file selection → AI streaming → doneinternal/ai/- AI client, session management, tool executioninternal/git/- Git operations (commit, diff, files, search, tools)internal/diff/- Three-tier diff degradation (full → compact → file-level)internal/config/- YAML config with env var overrides (AI_API_KEY,AI_MODEL,AI_BASE_URL)internal/skill/- Skill system (MCP-based extensible tool plugins)internal/mcp/- MCP (Model Context Protocol) client for external tool serversinternal/memory/- Project memory persistence (.git/ai-memory)internal/logger/- Structured logging to~/.config/ai-commit/logs/
AI tool flow: User selects files → stage → AI starts immediately → AI uses ReAct loop (Thought → Action → Observation) with all available tools (diff_overview, read_file, git_status, git_log, report_review, ask_user, git_commit, etc.) → commit → verify
ReAct Agent pattern: AI operates in a continuous loop: (1) Think about current state, (2) Call tools to gather information or take action, (3) Observe results, (4) Repeat until commit succeeds or user cancels. Tool errors are fed back to AI for autonomous error handling.
No-tool-call handling: If AI outputs text without calling any tools, the system sends a reminder message (up to 2 times) prompting the AI to call tools. After 2 consecutive no-tool-call responses, a fallback commit is forced using extracted or default commit message. This prevents the AI from "giving up" without committing.
Git as a tool: AI has free access to all Git operations (status/log/branch/stash/add/restore/diff/blame/tag). No rigid execution order. AI uses ask_user to confirm commit message before calling git_commit.
Basic flow preserved: TUI stages selected files and computes diff before starting AI session. AI receives diff context immediately, allowing it to focus on review and commit rather than basic setup operations.
Commit message quality: The prompt enforces specific, meaningful commit messages. Generic subjects like "提交变更", "添加功能", "修复问题" are explicitly forbidden. The AI must describe what was actually changed (e.g., "feat(auth): 添加 OAuth2 登录支持").
Critical patterns
Diff degradation: Auto-selects strategy by byte count (full → compact summary sorted by change size → file list + on-demand read_diff)
Large change handling: Enhanced diff_overview tool provides file type categorization (core/test/config/generated/docs) to help AI prioritize. System prompt includes 4-step strategy: (1) global scan, (2) priority ranking, (3) deep reading with context, (4) cross-file impact analysis. Initial diff limits increased to 8000 chars (normal) / 4000 chars (compact) for better context.
Code understanding enhancements: Three improvements to help AI better understand code changes:
- Enhanced diff context: Changed from
--unified=1to--unified=5to show more surrounding code context in diffs - Deep understanding prompt: System prompt now includes guidance for reading complete function definitions, understanding change intent, analyzing impact scope, checking boundary conditions, and verifying logic completeness
- analyze_changed_functions tool: New tool that extracts complete function definitions for changed code. For Go files, uses AST-based heuristics to identify functions containing changes and returns their full code with line numbers. For other languages, returns enhanced diff with 10 lines of context.
Task management: manage_tasks tool helps AI track review progress and coordinate multi-step workflows:
- Auto-generation:
manage_tasks(action='create', auto_generate=true)creates analysis tasks for each staged file, plus review and commit tasks - Progress tracking: AI marks tasks as completed after analyzing each file, ensuring no files are missed
- Issue recording: AI can add issue-type tasks to record problems found during review
- Workflow coordination: Helps AI plan and execute complex review tasks systematically
- Task storage is in-memory within CommitSession, persisted only for the current session
Token management: Estimates tokens at startup; >85% context window triggers compact mode (aggressive truncation + shorter prompt). Conversation history auto-compresses in-memory after each round (keeps last 3 tool results, discards older read_file/list_tree/diff_overview results) to prevent OOM on long sessions.
Model-specific features: ReasoningContent field (for thinking/reasoning tokens) is only supported by DeepSeek models. Setting it for other models (Qwen, GPT, etc.) causes API errors (Invalid type for 'messages.[0].content'). Always check model name before setting ReasoningContent on assistant messages.
Session timeout: 10-minute timeout protection prevents infinite loops. Timeout errors are distinguished from user cancellations and AI failures in error messages.
Error handling: Distinguishes between user cancel (exit 130), AI failure (exit 2), and timeout (exit 4). Error reasons are logged and displayed to users with actionable suggestions.
Truncation detection: finish_reason=length + heuristic rules → auto-retry with degradation or extract commit message from truncated output
Concurrent tools: Non-commit tools run in parallel; commit tools run serially. read_file/list_tree have call limits to prevent token waste.
Adaptive read_file limits: Dynamic call limits based on changed file count (<3 files: 4 calls, <10: 8, <25: 12, ≥25: 16). Override with GIT_AI_MAX_READ_FILE_CALLS env var.
Session continue: Saves conversation to .git/ai-session.json after commit. --continue flag reuses history + appends new changes.
TUI gotchas
- WindowSizeMsg must forward to both parent and Panel, else internal viewport never initializes (
vpReady=false) - Spinner.Update must run in Panel.Update() default branch, else spinner stops
- StreamActor.Run() returns
tea.Cmd(usesNextMsgCmd), nottea.Msg - contentH must clamp to ≥1 after subtraction
- Overlay is a bottom confirmation bar, not a screen overlay (replaces FooterBar). Required for
git_commit,git_commit_amend, andsummarize_changes(unless--auto-confirm). AI may also useask_usertool for other confirmations. - renderMarkdown needs
Width()set on all lines for wrapping - Viewport sizing:
SetViewportSizemust be called once after Panel creation;WindowSizeMsgmust forward to Panel on resize
TUI features
Mouse scrolling: All panels (streaming, done, file selector) support mouse wheel scrolling. tea.WithMouseCellMotion() is enabled at program level, and viewports have MouseWheelEnabled = true.
Smart auto-scroll: Streaming panel only auto-scrolls to bottom if user is already near the bottom (within 3 lines). If user scrolls up to read history, new content won't snap them back to bottom.
File selector folder grouping: Files are grouped by directory with collapsible folders. Use Tab to toggle folder collapse. Folder headers show selection count (e.g., ▼ src (3/5)). Files are indented under their parent folder. Navigation keys (↑↓/j/k) work with the virtual display list that includes folder headers.
File type priority
internal/git/priority.go weights files: core (1.5x), test (0.3x), config (0.5x), generated (0.1x)
Tech stack
Go 1.24, bubbletea (TUI), lipgloss (styles), go-openai (OpenAI-compatible API for DeepSeek/Qwen/OpenAI)
Behavioral notes
- Avoid Python scripts for file modifications except batch operations
- For batch operations (rename, move, replace), review confirmation list before executing
- macOS file descriptor limit: auto-raises soft limit (256 → hard limit) at startup to avoid exhaustion with TUI + git subprocesses