Add the AI layer that turns scan results into suggested next actions. Provider model (internal/ai): - Provider interface with Name() and Suggest(ctx, ScanResult) returning []Suggestion (repo_path, action, message, command, priority 0-2) - NewProvider factory resolves the configured provider and enforces that cloud providers have their API key in the configured env var; Ollama needs no key - OpenAIProvider: Chat Completions with response_format json_object - OllamaProvider: local /api/chat with format:json for structured output - AnthropicProvider: Messages API with system prompt and key/version headers; all three fall back to provider-appropriate defaults for base_url and model - Shared client: 60s timeout, 4 MiB response cap, JSON encode/decode, HTTP error surfaces the upstream status and body Prompt design (BuildPrompt): - Renders the full repository status table (name/status/branch/ahead/ behind/changes) plus strict output rules: exact suggestion schema, allowed actions, smallest-safe-step guidance, no invented repositories, return [] when healthy Parsing (parseSuggestions): - Tolerates ```json fences and surrounding prose, clamps priorities to 0-2, caps the result, and rejects replies without a JSON array Suggestion display (presenter.Suggestions): - "AI SUGGESTIONS" table (repository/action/priority/message/command) rendered below the scan table with priority color-coded (red/yellow/ green); empty results say all repositories are healthy Guarded execution (--ai-execute, experimental): - RunConfirmed executes a suggestion's command inside its repository only after explicit per-command y/N confirmation, and only for actions on an allowlist (commit/push/pull/stash/checkout) so LLM output can never run arbitrary shell commands; cancellation aborts remaining suggestions CLI wiring: - scan: AI block after the table when --ai is set and format is not json (JSON streams stay machine-readable); failures degrade to warnings - watch: AI is queried only on the first frame and when something changed since the previous frame, to avoid hammering the provider every interval - New --ai-execute flag and provider validation in config (openai/ollama/ anthropic), included in the config dump Testing: - httptest-based provider tests verifying request shape (model, auth headers, path), response parsing, API error bodies, HTTP failures, and cancellation - Parse tests: plain/fenced/prose replies, empty arrays, garbage, truncated JSON, priority clamping - Execution tests: unsafe actions and empty commands never run, declined confirmations are skipped, confirmed commands execute in the repo dir, failing commands surface errors - Presenter suggestion table and empty-state tests Verified: go build, go vet, go test -race, gofmt clean; end-to-end smoke test against a local fake Ollama server (request shape confirmed, table + suggestions rendered) and the missing-API-key warning path.
179 lines
5.6 KiB
Go
179 lines
5.6 KiB
Go
package presenter
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.oblak.solutions/dimitar/gitFlow/internal/ai"
|
|
"gitea.oblak.solutions/dimitar/gitFlow/pkg/status"
|
|
)
|
|
|
|
func sampleResult() status.ScanResult {
|
|
return status.ScanResult{
|
|
ScannedAt: time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),
|
|
ParentDir: "/home/user/projects",
|
|
Repos: []status.RepoInfo{
|
|
{Path: "/home/user/projects/api", Name: "api", Branch: "main", Status: status.StatusClean},
|
|
{
|
|
Path: "/home/user/projects/web",
|
|
Name: "web",
|
|
Branch: "feat/login",
|
|
Status: status.StatusModified,
|
|
ModifiedFiles: []string{"a.go"},
|
|
UntrackedFiles: []string{"b"},
|
|
AheadBy: 3,
|
|
},
|
|
{Path: "/home/user/projects/lib", Name: "lib", Branch: "main", Status: status.StatusBehind, BehindBy: 5},
|
|
{Path: "/home/user/projects/legacy", Name: "legacy", Branch: "(detached)", Detached: true, Status: status.StatusDetached},
|
|
{Path: "/home/user/projects/broken", Name: "broken", Status: status.StatusError, Error: "git status: fatal: not a git repository"},
|
|
},
|
|
}
|
|
}
|
|
|
|
func TestParseColorMode(t *testing.T) {
|
|
cases := []struct {
|
|
in string
|
|
want ColorMode
|
|
}{
|
|
{"auto", ColorAuto},
|
|
{"always", ColorAlways},
|
|
{"never", ColorNever},
|
|
{"bogus", ColorAuto},
|
|
}
|
|
for _, tc := range cases {
|
|
if got := ParseColorMode(tc.in); got != tc.want {
|
|
t.Errorf("ParseColorMode(%q) = %v, want %v", tc.in, got, tc.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestTableFormat(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
opts := Options{Color: ColorNever}
|
|
if err := Present(&buf, "table", sampleResult(), opts); err != nil {
|
|
t.Fatalf("Present: %v", err)
|
|
}
|
|
out := buf.String()
|
|
for _, want := range []string{
|
|
"REPOSITORY", "BRANCH", "STATUS", "AHEAD/BEHIND", "CHANGES",
|
|
"api", "feat/login", "1M 1U", "0/5", "3/0",
|
|
"5 repos | 1 clean | 3 need attention | 1 errors",
|
|
"not a git repository",
|
|
} {
|
|
if !strings.Contains(out, want) {
|
|
t.Errorf("table output missing %q:\n%s", want, out)
|
|
}
|
|
}
|
|
if strings.Contains(out, "\x1b[") {
|
|
t.Errorf("table output contains escape codes with ColorNever:\n%q", out)
|
|
}
|
|
}
|
|
|
|
func TestTableColorAlways(t *testing.T) {
|
|
t.Setenv("NO_COLOR", "1") // explicit always must win over NO_COLOR
|
|
var buf bytes.Buffer
|
|
if err := Present(&buf, "table", sampleResult(), Options{Color: ColorAlways}); err != nil {
|
|
t.Fatalf("Present: %v", err)
|
|
}
|
|
if !strings.Contains(buf.String(), "\x1b[") {
|
|
t.Error("ColorAlways produced no escape codes")
|
|
}
|
|
}
|
|
|
|
func TestTableRespectsNoColor(t *testing.T) {
|
|
t.Setenv("NO_COLOR", "1")
|
|
var buf bytes.Buffer
|
|
// ColorAuto with a non-terminal writer: no color regardless of NO_COLOR,
|
|
// but this also verifies NO_COLOR is read without panicking.
|
|
if err := Present(&buf, "table", sampleResult(), Options{Color: ColorAuto}); err != nil {
|
|
t.Fatalf("Present: %v", err)
|
|
}
|
|
if strings.Contains(buf.String(), "\x1b[") {
|
|
t.Error("auto color on non-TTY writer produced escape codes")
|
|
}
|
|
}
|
|
|
|
func TestJSONFormat(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
if err := Present(&buf, "json", sampleResult(), Options{}); err != nil {
|
|
t.Fatalf("Present: %v", err)
|
|
}
|
|
var doc struct {
|
|
ScannedAt time.Time `json:"scanned_at"`
|
|
ParentDir string `json:"parent_dir"`
|
|
Repos []status.RepoInfo `json:"repos"`
|
|
Summary status.Summary `json:"summary"`
|
|
}
|
|
if err := json.Unmarshal(buf.Bytes(), &doc); err != nil {
|
|
t.Fatalf("output is not valid JSON: %v\n%s", err, buf.String())
|
|
}
|
|
if doc.ParentDir != "/home/user/projects" {
|
|
t.Errorf("parent_dir = %q", doc.ParentDir)
|
|
}
|
|
if len(doc.Repos) != 5 {
|
|
t.Errorf("len(repos) = %d, want 5", len(doc.Repos))
|
|
}
|
|
if doc.Repos[1].Status != status.StatusModified {
|
|
t.Errorf("repos[1].status = %v, want modified", doc.Repos[1].Status)
|
|
}
|
|
if doc.Summary.Total != 5 || doc.Summary.Clean != 1 || doc.Summary.Attention != 3 || doc.Summary.Errored != 1 {
|
|
t.Errorf("summary = %+v", doc.Summary)
|
|
}
|
|
// Status must marshal as a string label, not an int.
|
|
if !strings.Contains(buf.String(), `"status": "modified"`) {
|
|
t.Errorf("status not marshaled as string label:\n%s", buf.String())
|
|
}
|
|
}
|
|
|
|
func TestCompactFormat(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
if err := Present(&buf, "compact", sampleResult(), Options{Color: ColorNever}); err != nil {
|
|
t.Fatalf("Present: %v", err)
|
|
}
|
|
out := buf.String()
|
|
for _, want := range []string{"✓", "✗", "↓", "◉", "!", "+3/-0", "2 change(s)"} {
|
|
if !strings.Contains(out, want) {
|
|
t.Errorf("compact output missing %q:\n%s", want, out)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestForRejectsUnknownFormat(t *testing.T) {
|
|
if _, err := For("xml", Options{}); err == nil {
|
|
t.Error("For(xml) succeeded, want error")
|
|
}
|
|
}
|
|
|
|
func TestSuggestions(t *testing.T) {
|
|
sugs := []ai.Suggestion{
|
|
{RepoPath: "/home/user/projects/web", Action: "commit", Message: "commit your work", Command: "git add -A && git commit -m wip", Priority: 2},
|
|
{RepoPath: "/home/user/projects/lib", Action: "pull", Message: "pull latest", Command: "git pull", Priority: 1},
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := Suggestions(&buf, Options{Color: ColorNever}, sugs); err != nil {
|
|
t.Fatalf("Suggestions: %v", err)
|
|
}
|
|
out := buf.String()
|
|
for _, want := range []string{"AI SUGGESTIONS", "commit", "pull", "high", "medium", "git pull"} {
|
|
if !strings.Contains(out, want) {
|
|
t.Errorf("suggestions output missing %q:\n%s", want, out)
|
|
}
|
|
}
|
|
if strings.Contains(out, "\x1b[") {
|
|
t.Errorf("suggestions contain escape codes with ColorNever")
|
|
}
|
|
}
|
|
|
|
func TestSuggestionsEmpty(t *testing.T) {
|
|
var buf bytes.Buffer
|
|
if err := Suggestions(&buf, Options{}, nil); err != nil {
|
|
t.Fatalf("Suggestions: %v", err)
|
|
}
|
|
if !strings.Contains(buf.String(), "no suggestions") {
|
|
t.Errorf("empty suggestions message missing: %q", buf.String())
|
|
}
|
|
}
|