diff --git a/CHANGELOG.md b/CHANGELOG.md index 27ce1c1..716fb00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,9 @@ Bu proje [Keep a Changelog](https://keepachangelog.com/tr/1.0.0/) biçimini ve S - **README görselleri yenilendi:** Tüm ekran görüntüleri güncel arayüzle (demo verisiyle) yeniden çekildi ve tarayıcı penceresi çerçevesine alınmış tek dosyalık SVG oldu (`scripts/ekran-cercevesi.py`; çekim: `tests/e2e/ekran-goruntuleri.mjs`). Eski `.webp` görüntüler kişisel tarayıcı sekmelerini/yer imlerini gösteriyordu; kaldırıldı. Merge Kuyruğu, Dal koruması ve MCP pencereleri için yeni görseller; "Kuyrukta biri kırmızı yandı" senaryosu eklendi. ### Düzeltilenler +- **MCP `gitarc_cleanup_candidates` var olmayan dalları aday sayıyor ve `release/*` için silme öneriyordu:** 13 adayın 10'u ne yerelde ne uzakta olan, yalnızca PR geçmişinden gelen adlardı (`suggestedCmd` boş), ve `release/0.10.0` için `git branch -D` önerilmişti (araç arayüzün tek kuralı `IsPrunable`'ı kullanmıyor, kendi koşulunu yazmıştı). Artık aday = `Prunable` ve dal gerçekten var; PR geçmişi adları `historyOnlyIgnored` olarak sayılır; aday yoksa `count: 0`, `candidates: []`. +- **MCP `gitarc_protection_status` Ruleset'li depoda içi boş döndürüyordu:** dala uygulanan Ruleset kuralları artık salt okunur okunur (`rules/branches/`: zorunlu CI, PR/onay, force-push, silme; `source: ruleset`). Okunamayan ya da korumasız durumda sıfır değerli `current` (`checks: null`) yerine `current: null` + `reason` döner ("korumasız" ile "okunamadı" ayrı). Koruma penceresindeki "Şu an" listesi de Ruleset'li depolarda artık gerçek kuralları gösterir. +- **MCP `gitarc_audit_log` proje belirsizdi:** her kayıt `repoId` + `repoName` taşır; varsayılan yalnızca seçili proje, `repoId="all"` ile tümü; projesi bilinmeyen eski kayıtlar varsayılanda gizli (sayısı `hiddenUnknownRepo`), yalnızca `all` ile "bilinmiyor" görünür. - **Yeni açılan PR'da düz "Merge" sunulup GitHub reddine çarpılıyordu (sshpocket #342/#343'te her seferinde):** GitHub zorunlu CI kontrollerini PR açıldıktan birkaç saniye sonra oluşturur; o aralıkta CI "bilinmiyor"du (yeşil varsayılmaz) ama düğme yine `⚡ Merge` idi, basınca `base branch policy prohibits the merge` hatası ve Hata Radarı kartı çıkıyordu (sunucu "CI bitince" koşusunu zaten sonradan başlatıp PR'ı birleştiriyordu). Artık: (1) varsayılan dalın zorunlu CI kontrolleri salt okunur okunur (`RepoMeta.requiredChecks`: Ruleset `rules/branches/` + klasik koruma; Ruleset'in "dal güncel olmalı" kuralı da `strictUpToDate`'e yansır, eskiden yalnızca klasik koruma okunuyordu); (2) CI henüz yokken zorunlu kontrol varsa düğme baştan `⏳ CI Bitince Merge Et` olur (`ciPendingForMerge`; zorunlu kontrol yok/okunamadıysa düz Merge kalır, CI'ı olmayan depoda boşuna beklenmez, "çalışıyor" uydurulmaz); (3) koruma engeli yine de olursa günlükte `error` değil `info` tutulur (Radar kartı çıkmaz), mesajdaki yanıltıcı "onay eksik" ifadesi kalktı. Testler: `required_checks_test.go`, `ci-pending.test.mjs` (eski kodda düşüyor). - **Omurga, GitHub'da varsayılan dal değişince eski dalda kalıyordu (`detectDefaultBranch`):** Klonun `origin/HEAD` kaydı klonlama anında yazılır ve `git fetch` onu güncellemez; varsayılanı `kurulum-v0.1`'den `main`'e çevrilmiş bir depoda GitArc eski dalı omurga aldı (asıl dal "Yarım Parabol · Local" çizildi, koruma/PR mesajları yanlış dalı söyledi, "Push & PR Aç" `No commits between main and ...` ile düştü). Arka plan fetch artık uzağın gerçek varsayılanını da okur (`git ls-remote --symref`, salt okunur; yerel ref'lere yazmaz) ve elle seçimden sonra ilk bu kullanılır; okunamazsa eski davranış. `gh pr create` omurgayı `--base` ile açıkça alır (uzakta varsa), böylece GitArc'ın "önde" hesabı ile GitHub'ın tabanı ayrışmaz. `TestDefaultBranchFollowsRemoteWhenLocalOriginHeadIsStale` eski kodda düşüyor. - **`main CI` rozeti merge'ten hemen sonra ESKİ commit'in yeşilini gösteriyordu (`fetchMainCI`):** GitHub, push'tan sonra yeni commit için iş akışı kaydını birkaç saniye geç açar; o aralıkta "en son koşu" bir önceki commit'e aittir ve rozet onu yeni merge'ün sonucu gibi `✓ main CI` gösterip yeni testlerin sürdüğünü gizliyordu (GitHub sayfası "in progress" derken GitArc yeşildi). Artık koşular omurganın GERÇEK ucuyla (`origin/`) karşılaştırılır: uç için koşu yoksa ve uç 15 dk'dan yeniyse `⏳ testleri koşuyor (başlıyor)`, eskiyse sonuç yok (rozet gizli); asla eski yeşil değil. `TestMainCIDoesNotShowStaleGreenForFreshTip` eski kodda düşüyor. diff --git a/README.md b/README.md index e4a0b9b..c684ce4 100644 --- a/README.md +++ b/README.md @@ -168,10 +168,10 @@ Arayüzdeki `🔌 MCP` düğmesi yapılandırmayı (çalışan GitArc ikilisinin | `gitarc_conflict_plan` | Bir daldaki çakışmayı salt okunur inceler: dosyalar, çakışma metni, stratejiler, riskler (salt okunur) | | `gitarc_resolve_conflict` | İzole worktree içinde doğrulamalı çakışma çözümü; yerel dalı günceller ve dalı uzağa **push eder**. **Varsayılan KAPALI**: yalnızca sunucu `GITARC_MCP_ALLOW_RESOLVE=1` ile başlatılırsa çalışır ve plandan alınan `fingerprint` ister | | `gitarc_propose_commit` | Commit & PR öneri kartı (arayüzde onay bekler, doğrudan commit etmez) | -| `gitarc_cleanup_candidates` | Temizlenebilir birleşmiş/silinmiş dallar ve kanıtları (silmez) | +| `gitarc_cleanup_candidates` | Temizlenebilir birleşmiş/silinmiş dallar ve kanıtları (silmez). Arayüzdeki 🧹 ile aynı kural: uzun ömürlü dallar (develop, release/*) ve yalnızca PR geçmişinde kalan (ne yerelde ne uzakta olan) adlar aday sayılmaz | | `gitarc_scan_secrets` | API anahtarı, özel anahtar, `.env` ve kişisel yol taraması | -| `gitarc_audit_log` | Kokpit ve MCP işlem kayıtları | -| `gitarc_protection_status` | Varsayılan dalın koruma durumu ve zorunlu yapılabilecek CI kontrolleri (salt okunur) | +| `gitarc_audit_log` | Kokpit ve MCP işlem kayıtları; her kayıt `repoId` + `repoName` taşır, varsayılan yalnızca seçili proje (`repoId="all"` ile tümü; projesi bilinmeyen eski kayıtlar yalnızca `all` ile "bilinmiyor" görünür) | +| `gitarc_protection_status` | Varsayılan dalın koruma durumu ve zorunlu yapılabilecek CI kontrolleri (salt okunur). Ruleset'le korunan depoda dala uygulanan kurallar (zorunlu CI, PR/onay, force-push, silme) salt okunur gösterilir (`source: ruleset`); okunamazsa `current: null` ve `reason` ("korumasız" DEĞİL) | | `gitarc_protection_plan` | Bir koruma profilinin ne değiştireceği (salt okunur; yalnızca güçlendirir) | | `gitarc_protection_apply` | Planı uygular. **Varsayılan KAPALI**: yalnızca sunucu `GITARC_MCP_ALLOW_PROTECTION=1` ile başlatılırsa çalışır ve plandan alınan `fingerprint` ister | diff --git a/internal/gitengine/audit_ruleset_test.go b/internal/gitengine/audit_ruleset_test.go new file mode 100644 index 0000000..a3e1f5e --- /dev/null +++ b/internal/gitengine/audit_ruleset_test.go @@ -0,0 +1,115 @@ +package gitengine + +import ( + "context" + "strings" + "testing" + + "gitarc/internal/model" +) + +// Ruleset'le korunan depoda koruma "ruleset" olarak bilinir ama içi görünmezdi (current boş). Artık dala uygulanan kurallar salt okunur okunur. +func TestProtectionPlanReadsRulesetRulesReadOnly(t *testing.T) { + stub := newGHStub(t) + dir, _ := newGitHubLikeRepo(t) + stub.set("api_protection_get", "Branch not protected", 1) // klasik koruma yok + stub.set("api_rulesets", `[{"id":1,"name":"main","target":"branch","enforcement":"active"}]`, 0) + stub.set("api_rules_branch", rulesBranchJSON, 0) + + mgr := NewManager(dir) + if _, err := mgr.SwitchRepo("live-custom"); err != nil { + t.Fatal(err) + } + plan, err := mgr.ProtectionPlan("temel", nil) + if err != nil { + t.Fatal(err) + } + if plan.State != "ruleset" || plan.Source != "ruleset" { + t.Fatalf("state=ruleset, source=ruleset beklenirdi: %+v", plan) + } + c := plan.Current + if !c.RequirePR || !c.BlockForcePush || !c.BlockDeletion || !c.StrictUpToDate || strings.Join(c.Checks, ",") != "go (ubuntu-26.04),web" { + t.Fatalf("Ruleset kuralları Current'a yansımalı: %+v", c) + } + if plan.Applicable { + t.Fatal("Ruleset'i GitArc değiştirmez: plan uygulanabilir olmamalı") + } + if stub.called("-X PUT") || stub.called("-X POST") { + t.Fatal("okuma sırasında hiçbir yazma çağrısı olmamalı") + } +} + +// Ruleset kuralları okunamazsa Source boş kalır ve neden yazılır ("okunamadı" ≠ "kural yok"). +func TestProtectionPlanRulesetUnreadableSaysSo(t *testing.T) { + stub := newGHStub(t) + dir, _ := newGitHubLikeRepo(t) + stub.set("api_protection_get", "Branch not protected", 1) + stub.set("api_rulesets", `[{"id":1,"name":"main","target":"branch","enforcement":"active"}]`, 0) + stub.set("api_rules_branch", "HTTP 403", 1) + mgr := NewManager(dir) + if _, err := mgr.SwitchRepo("live-custom"); err != nil { + t.Fatal(err) + } + plan, err := mgr.ProtectionPlan("temel", nil) + if err != nil { + t.Fatal(err) + } + if plan.State != "ruleset" || plan.Source != "" { + t.Fatalf("kurallar okunamadı: state=ruleset, source boş beklenirdi: %+v", plan) + } + joined := strings.Join(plan.Notes, " | ") + if !strings.Contains(joined, "okunamadı") { + t.Fatalf("neden yazılmalı: %s", joined) + } +} + +func TestReadRulesetSettingsParsesApprovals(t *testing.T) { + stub := newGHStub(t) + dir, _ := newGitHubLikeRepo(t) + stub.set("api_rules_branch", `[{"type":"pull_request","parameters":{"required_approving_review_count":2,"dismiss_stale_reviews_on_push":true}}]`, 0) + s, ok := readRulesetSettings(context.Background(), dir, "main") + if !ok || !s.RequirePR || s.Approvals != 2 || !s.DismissStale || s.BlockForcePush { + t.Fatalf("pull_request kuralı okunmalı, diğerleri kapalı: ok=%v %+v", ok, s) + } +} + +// Denetim günlüğü: her kayıt proje kimliği + adıyla döner; varsayılan yalnızca etkin proje; repoId'siz eski kayıtlar gizli (sayılır), yalnızca +// "all" ile "bilinmiyor" olarak görünür. Başka projenin kaydı ("PR #102 ...") bu projede görünmez. +func TestAuditLogsScopeAndLegacyHandling(t *testing.T) { + dir, _ := newTempRepo(t) + mgr := NewManager(dir) + if _, err := mgr.SwitchRepo("live-custom"); err != nil { + t.Fatal(err) + } + mgr.mu.Lock() + mgr.logs = []model.ActionLogEntry{ + {ID: "l1", RepoID: "live-custom", Action: "A", Message: "bu proje"}, + {ID: "l2", RepoID: "baska-proje", Action: "B", Message: "PR #102 başka projeye ait"}, + {ID: "l3", RepoID: "", Action: "C", Message: "eski kayıt, projesi bilinmiyor"}, + } + mgr.mu.Unlock() + + logs, scope, hidden := mgr.AuditLogs("", 25) + if scope != "live-custom" || len(logs) != 1 || logs[0].ID != "l1" || logs[0].RepoName == "" || logs[0].RepoID != "live-custom" { + t.Fatalf("varsayılan: yalnızca etkin proje, kimlik+ad ile: scope=%s %+v", scope, logs) + } + if hidden != 1 { + t.Fatalf("repoId'siz eski kayıt gizlenip sayılmalı: hidden=%d", hidden) + } + all, scope2, _ := mgr.AuditLogs("all", 25) + if scope2 != "all" || len(all) != 3 { + t.Fatalf("all: tüm kayıtlar beklenirdi: %d", len(all)) + } + for _, e := range all { + if e.ID == "l3" && (e.RepoID != "bilinmiyor" || e.RepoName != "bilinmiyor") { + t.Fatalf("eski kayıt 'bilinmiyor' işaretlenmeli: %+v", e) + } + if e.ID == "l2" && e.RepoName != "baska-proje" { + t.Fatalf("listede olmayan proje için kimlik gösterilmeli: %+v", e) + } + } + other, _, _ := mgr.AuditLogs("baska-proje", 25) + if len(other) != 1 || other[0].ID != "l2" { + t.Fatalf("belirli proje: yalnızca onun kaydı: %+v", other) + } +} diff --git a/internal/gitengine/protection.go b/internal/gitengine/protection.go index 3a4dd58..ca5f897 100644 --- a/internal/gitengine/protection.go +++ b/internal/gitengine/protection.go @@ -227,8 +227,9 @@ func buildPlan(branch, profile string, selected []string, cur model.ProtectionSe // ---- Canlı (GitHub) ---- type ghProtectionRead struct { - settings model.ProtectionSettings - raw map[string]json.RawMessage + settings model.ProtectionSettings + raw map[string]json.RawMessage + fromRuleset bool // settings, Ruleset kurallarından (salt okunur) okundu } func ghAPIBranchPath(branch string) string { @@ -257,16 +258,65 @@ func readLiveProtection(ctx context.Context, repoPath, branch string) (ghProtect return res, "unsupported" case strings.Contains(low, "branch not protected"): if hasActiveRuleset(ctx, repoPath) { + res.settings, res.fromRuleset = readRulesetSettings(ctx, repoPath, branch) return res, "ruleset" } return res, "none" } if hasActiveRuleset(ctx, repoPath) { + res.settings, res.fromRuleset = readRulesetSettings(ctx, repoPath, branch) return res, "ruleset" } return res, "unknown" } +// readRulesetSettings: dala UYGULANAN GitHub Ruleset kurallarını (`rules/branches/`; okuma yetkisi yeter) ProtectionSettings'e çevirir. +// SALT OKUNUR: GitArc Ruleset'i değiştirmez. ok=false: kurallar okunamadı (çağıran "yok" değil "okunamadı" der). +// Yöneticiler için geçerlilik (enforceAdmins) bu uçtan bilinmez (bypass listesi ayrı); false bırakılır. +func readRulesetSettings(ctx context.Context, repoPath, branch string) (model.ProtectionSettings, bool) { + var s model.ProtectionSettings + out, _, err := runCmd(ctx, repoPath, "gh", "api", "repos/:owner/:repo/rules/branches/"+branch) + if err != nil { + return s, false + } + var rules []struct { + Type string `json:"type"` + Parameters struct { + Required []struct { + Context string `json:"context"` + } `json:"required_status_checks"` + Strict bool `json:"strict_required_status_checks_policy"` + Approvals int `json:"required_approving_review_count"` + DismissStale bool `json:"dismiss_stale_reviews_on_push"` + } `json:"parameters"` + } + if json.Unmarshal([]byte(out), &rules) != nil { + return s, false + } + for _, r := range rules { + switch r.Type { + case "pull_request": + s.RequirePR = true + if r.Parameters.Approvals > s.Approvals { + s.Approvals = r.Parameters.Approvals + } + s.DismissStale = s.DismissStale || r.Parameters.DismissStale + case "required_status_checks": + for _, c := range r.Parameters.Required { + if c.Context != "" { + s.Checks = append(s.Checks, c.Context) + } + } + s.StrictUpToDate = s.StrictUpToDate || r.Parameters.Strict + case "non_fast_forward": + s.BlockForcePush = true + case "deletion": + s.BlockDeletion = true + } + } + return s, true +} + func hasActiveRuleset(ctx context.Context, repoPath string) bool { out, _, err := runCmd(ctx, repoPath, "gh", "api", "repos/:owner/:repo/rulesets") if err != nil || strings.TrimSpace(out) == "" || strings.TrimSpace(out) == "[]" { @@ -443,6 +493,14 @@ func (m *Manager) livePlan(ctx context.Context, live *repoEntry, profile string, } read, state := readLiveProtection(ctx, live.path, branch) plan, err := buildPlan(branch, profile, checks, read.settings, state, fetchAvailableChecks(ctx, live.path, branch)) + switch { + case state == "active": + plan.Source = "classic" + case state == "ruleset" && read.fromRuleset: + plan.Source = "ruleset" + case state == "ruleset": + plan.Notes = append(plan.Notes, "Ruleset kuralları okunamadı (ayrıntı gösterilemiyor); bu \"kural yok\" demek değildir.") + } return plan, read.raw, err } diff --git a/internal/gitengine/simulation.go b/internal/gitengine/simulation.go index faedba1..77e43d7 100644 --- a/internal/gitengine/simulation.go +++ b/internal/gitengine/simulation.go @@ -496,6 +496,50 @@ func (m *Manager) recentLogs() []model.ActionLogEntry { return m.recentLogsLocked() } +// AuditLogs: denetim günlüğü (MCP). repoID: "" = etkin proje, "all" = tüm projeler, aksi halde o proje. Her kayıt proje kimliği VE adıyla +// döner. repoID'si olmayan eski kayıtlar ("bilinmiyor": hangi projeye ait olduğu bilinmez) varsayılanda (yalnızca etkin proje) ve belirli bir +// projede GİZLENİR ve sayısı döner; yalnızca "all" ile görünür (RepoID "bilinmiyor" yazılır). limit<=0: 25. +func (m *Manager) AuditLogs(repoID string, limit int) (logs []model.ActionLogEntry, scopeID string, hiddenUnknown int) { + if limit <= 0 { + limit = 25 + } + m.mu.RLock() + defer m.mu.RUnlock() + names := map[string]string{} + for _, o := range m.repoOptionsLocked() { + names[o.ID] = o.Name + } + scopeID = strings.TrimSpace(repoID) + if scopeID == "" { + scopeID = m.activeRepoID + } + out := []model.ActionLogEntry{} + for _, e := range m.logs { + if e.RepoID == "" { + if scopeID == "all" && len(out) < limit { + e.RepoID, e.RepoName = "bilinmiyor", "bilinmiyor" + out = append(out, e) + } else if scopeID != "all" { + hiddenUnknown++ + } + continue + } + if scopeID != "all" && e.RepoID != scopeID { + continue + } + if len(out) >= limit { + continue + } + if n, ok := names[e.RepoID]; ok { + e.RepoName = n + } else { + e.RepoName = e.RepoID // proje artık listede değil: kimliği göster + } + out = append(out, e) + } + return out, scopeID, hiddenUnknown +} + // ClearLogs empties the in-memory cockpit operation/error log buffer and clears the persistent file. func (m *Manager) ClearLogs() (model.CockpitSnapshot, error) { m.mu.Lock() diff --git a/internal/mcp/cleanup_protection_test.go b/internal/mcp/cleanup_protection_test.go new file mode 100644 index 0000000..ff205dd --- /dev/null +++ b/internal/mcp/cleanup_protection_test.go @@ -0,0 +1,111 @@ +package mcp + +import ( + "encoding/json" + "testing" + + "gitarc/internal/model" +) + +func branch(name string, f func(*model.BranchArc)) model.BranchArc { + b := model.BranchArc{ID: "br-" + name, Name: name, State: "merged"} + f(&b) + return b +} + +// cleanup_candidates: arayüzdeki 🧹 sayacıyla AYNI kural (Prunable) + dal gerçekten var; yalnızca PR geçmişinden gelen adlar ve uzun ömürlü +// dallar aday DEĞİL. Gerçek hata: 13 "aday"ın 10'u hiçbir yerde olmayan adlardı, `release/*` için `git branch -D` önerilmişti. +func TestCleanupCandidatesOnlyRealPrunableBranches(t *testing.T) { + merged := &model.PRStatus{Number: 9, ReviewState: "MERGED"} + snap := model.CockpitSnapshot{ + Repo: model.RepoMeta{Mode: "live", Name: "demo"}, + Branches: []model.BranchArc{ + // uzakta duran, PR'ı MERGED dal → aday + branch("feat/uzakta", func(b *model.BranchArc) { b.HasRemote, b.PR, b.Prunable, b.SuggestedCmd = true, merged, true, "git push origin --delete feat/uzakta && git fetch --prune origin" }), + // squash ile birleşmiş, uzakta silinmiş yerel kopya → aday + branch("feat/squash", func(b *model.BranchArc) { b.HasLocal, b.OriginGone, b.PR, b.Prunable, b.SuggestedCmd = true, true, merged, true, "git branch -D feat/squash && git fetch --prune origin" }), + // yalnızca PR geçmişi: ne yerelde ne uzakta → aday DEĞİL (yalnızca sayılır) + branch("feat/gecmis-1", func(b *model.BranchArc) { b.PR, b.Prunable = merged, true }), + branch("feat/gecmis-2", func(b *model.BranchArc) { b.PR = merged }), + // uzun ömürlü dal: Prunable false → aday DEĞİL + branch("release/0.10.0", func(b *model.BranchArc) { b.HasLocal, b.HasRemote, b.OriginGone, b.LongLived, b.PR = true, true, true, true, merged }), + // açık, birleşmemiş dal + {ID: "br-acik", Name: "feat/acik", State: "open", HasLocal: true, HasRemote: true}, + }, + } + p := buildCleanupCandidatesPayload(snap) + raw, _ := json.Marshal(p) + var got struct { + Mode, Repo string + Count int + Candidates []struct{ Name, SuggestedCmd string } + HistoryOnlyIgnored int + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + if got.Count != 2 || len(got.Candidates) != 2 { + t.Fatalf("yalnızca gerçekten var olan 2 aday beklenirdi: %+v", got) + } + for _, c := range got.Candidates { + if c.Name == "release/0.10.0" || c.Name == "feat/gecmis-1" || c.Name == "feat/gecmis-2" { + t.Fatalf("aday olmamalı: %s", c.Name) + } + if c.SuggestedCmd == "" { + t.Fatalf("var olan dal için silme komutu önerilmeli: %s", c.Name) + } + } + if got.HistoryOnlyIgnored != 2 || got.Mode != "live" { + t.Fatalf("PR geçmişi adları sayılmalı ve mode yazılmalı: %+v", got) + } +} + +func TestCleanupCandidatesEmptyIsZeroAndNotNull(t *testing.T) { + p := buildCleanupCandidatesPayload(model.CockpitSnapshot{Repo: model.RepoMeta{Mode: "live"}}) + if p["count"].(int) != 0 { + t.Fatalf("aday yoksa count=0: %v", p["count"]) + } + raw, _ := json.Marshal(p) + var m map[string]any + _ = json.Unmarshal(raw, &m) + if arr, ok := m["candidates"].([]any); !ok || len(arr) != 0 { + t.Fatalf("candidates null değil boş dizi olmalı: %v", m["candidates"]) + } +} + +// protection_status: okunamayan koruma "korumasız" (sıfır değerli current, checks: null) gibi görünmemeli; neden yazılmalı. +func TestProtectionStatusPayloadHonestStates(t *testing.T) { + read := model.ProtectionSettings{RequirePR: true, Checks: []string{"web", "go"}, StrictUpToDate: true} + cases := []struct { + name string + plan model.ProtectionPlan + wantCur bool + wantReason bool + wantSource string + }{ + {"classic", model.ProtectionPlan{State: "active", Source: "classic", Current: read}, true, false, "classic"}, + {"ruleset okundu", model.ProtectionPlan{State: "ruleset", Source: "ruleset", Current: read}, true, false, "ruleset"}, + {"ruleset okunamadı", model.ProtectionPlan{State: "ruleset", Notes: []string{"Ruleset kuralları okunamadı"}}, false, true, ""}, + {"unknown (yetki yok)", model.ProtectionPlan{State: "unknown", Notes: []string{"Koruma durumu okunamadı (yetki yok)"}}, false, true, ""}, + {"korumasız", model.ProtectionPlan{State: "none"}, false, true, ""}, + } + for _, c := range cases { + p := protectionStatusPayload("live", c.plan, false) + cur, has := p["current"] + if c.wantCur && (!has || cur == nil) { + t.Errorf("%s: current dolu olmalı", c.name) + } + if !c.wantCur && cur != nil { + t.Errorf("%s: current boş (null) olmalı, sıfır değerli nesne 'korumasız' gibi okunur: %v", c.name, cur) + } + if _, ok := p["reason"]; ok != c.wantReason { + t.Errorf("%s: reason beklentisi %v", c.name, c.wantReason) + } + if src, _ := p["source"].(string); src != c.wantSource { + t.Errorf("%s: source=%q, beklenen %q", c.name, src, c.wantSource) + } + if p["mode"] != "live" || p["state"] != c.plan.State { + t.Errorf("%s: mode/state eksik: %v", c.name, p) + } + } +} diff --git a/internal/mcp/protection_tools.go b/internal/mcp/protection_tools.go index 7df230b..484eae6 100644 --- a/internal/mcp/protection_tools.go +++ b/internal/mcp/protection_tools.go @@ -5,6 +5,7 @@ import ( "strings" "gitarc/internal/gitengine" + "gitarc/internal/model" ) // Dal koruması araçları (oku → planla → [izinli] uygula). @@ -91,15 +92,7 @@ func callProtectionTool(name string, args map[string]any, mgr *gitengine.Manager if err != nil { return errResult(err.Error()), true } - return jsonTextResult(map[string]any{ - "mode": modeOf(mgr), - "branch": plan.Branch, - "state": plan.State, - "current": plan.Current, - "availableChecks": plan.AvailableChecks, - "notes": plan.Notes, - "applyEnabled": protectionApplyEnabled(), - }), true + return jsonTextResult(protectionStatusPayload(modeOf(mgr), plan, protectionApplyEnabled())), true case "gitarc_protection_plan": profile, _ := args["profile"].(string) @@ -145,3 +138,47 @@ func callProtectionTool(name string, args map[string]any, mgr *gitengine.Manager } return toolResult{}, false } + +// firstNote: plan notlarından "okunamadı/yok" ile ilgili ilkini ya da varsayılanı döndürür. +func firstNote(notes []string, def string) string { + for _, n := range notes { + if strings.Contains(n, "okunamadı") || strings.Contains(n, "Ruleset") || strings.Contains(n, "planında") { + return n + } + } + return def +} + +// protectionStatusPayload: gitarc_protection_status çıktısı (saf; sınanabilir). "current" yalnızca GERÇEKTEN okunduysa verilir. +func protectionStatusPayload(mode string, plan model.ProtectionPlan, applyEnabled bool) map[string]any { + res := map[string]any{ + "mode": mode, + "branch": plan.Branch, + "state": plan.State, + "availableChecks": plan.AvailableChecks, + "notes": plan.Notes, + "applyEnabled": applyEnabled, + } + // "current" yalnızca GERÇEKTEN okunduysa verilir (klasik koruma ya da Ruleset kuralları). Okunamadıysa/korumasızsa sıfır değerli + // bir nesne ("checks: null") "korumasız" gibi okunurdu: bunun yerine neden yazılır. + switch { + case plan.State == "unknown": + res["current"] = nil + res["reason"] = firstNote(plan.Notes, "Koruma durumu okunamadı (yetki yok ya da gh hatası); bu \"korumasız\" demek değildir.") + case plan.State == "none": + res["current"] = nil + res["reason"] = "Dal korumasız: zorunlu PR/CI kuralı yok." + case plan.State == "unsupported": + res["current"] = nil + res["reason"] = firstNote(plan.Notes, "Bu depo planında dal koruması yok.") + case plan.State == "ruleset" && plan.Source != "ruleset": + res["current"] = nil + res["reason"] = firstNote(plan.Notes, "Dal Ruleset ile korunuyor ama kurallar okunamadı.") + default: + res["current"] = plan.Current + if plan.Source != "" { + res["source"] = plan.Source // classic | ruleset (ruleset salt okunur: GitArc değiştirmez) + } + } + return res +} diff --git a/internal/mcp/server.go b/internal/mcp/server.go index 1c8424e..80453e1 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -262,7 +262,7 @@ func listTools() []toolDefinition { }, { Name: "gitarc_audit_log", - Description: "GitArc kokpiti ve MCP üzerinden gerçekleştirilen son işlemleri, önerileri ve onay kayıtlarını zaman damgalı olarak listeler.", + Description: "GitArc kokpiti ve MCP üzerinden gerçekleştirilen son işlemleri, önerileri ve onay kayıtlarını zaman damgalı olarak listeler. Her kayıt hangi projeye (repoId, repoName) ait olduğunu söyler; varsayılan yalnızca seçili projedir.", InputSchema: map[string]any{ "type": "object", "properties": map[string]any{ @@ -270,6 +270,10 @@ func listTools() []toolDefinition { "type": "integer", "description": "Döndürülecek maksimum log kaydı sayısı (varsayılan: 25).", }, + "repoId": map[string]any{ + "type": "string", + "description": "Varsayılan: yalnızca seçili (etkin) proje. \"all\" = tüm projeler; ya da bir proje kimliği. Her kayıt repoId ve repoName taşır; repoId'si olmayan eski kayıtlar yalnızca \"all\" ile \"bilinmiyor\" olarak görünür.", + }, }, }, }, @@ -369,34 +373,41 @@ func callTool(params toolCallParams, mgr *gitengine.Manager) toolResult { return jsonTextResult(buildScanSecretsPayload(paths, mgr)) case "gitarc_audit_log": - snap, err := mgr.Snapshot() - if err != nil { - return errResult(err.Error()) - } limit := 25 if l, ok := params.Arguments["limit"].(float64); ok && l > 0 { limit = int(l) } - logs := snap.Logs - if len(logs) > limit { - logs = logs[:limit] + repoID, _ := params.Arguments["repoId"].(string) + logs, scope, hidden := mgr.AuditLogs(repoID, limit) + snap, err := mgr.Snapshot() + if err != nil { + return errResult(err.Error()) } mode := snap.Repo.Mode if mode == "" { mode = "live" } - return jsonTextResult(map[string]any{ + res := map[string]any{ "mode": mode, + "scope": scope, // etkin proje kimliği ya da "all" "repo": snap.Repo.Name, "count": len(logs), "logs": logs, - }) + } + if hidden > 0 { + res["hiddenUnknownRepo"] = hidden // repoId'si olmayan eski kayıtlar; repoId="all" ile görünür + } + return jsonTextResult(res) default: return errResult(fmt.Sprintf("bilinmeyen araç: %s", params.Name)) } } +// buildCleanupCandidatesPayload: temizlenebilir dallar. Aday kuralı arayüzdeki "🧹 Temizle" sayacıyla AYNI ve tektir +// (`gitengine.IsPrunable` → `BranchArc.Prunable`): uzun ömürlü dallar (develop, release/*), kaydedilmemiş değişikliği olan aktif dal, +// uzakta ilerlemiş dallar hariç. Ek koşul: dal GERÇEKTEN var (yerelde ya da uzakta). Yalnızca PR geçmişinden gelen birleşmiş adlar +// (ne yerelde ne uzakta) aday DEĞİLDİR; `historyOnlyIgnored` olarak sayılır ki "N aday" yalan söylemesin. func buildCleanupCandidatesPayload(snap model.CockpitSnapshot) map[string]any { type cleanupCandidate struct { Name string `json:"name"` @@ -408,62 +419,49 @@ func buildCleanupCandidatesPayload(snap model.CockpitSnapshot) map[string]any { Proof string `json:"proof"` SuggestedCmd string `json:"suggestedCmd"` } - var candidates []cleanupCandidate + candidates := []cleanupCandidate{} + historyOnly := 0 for _, b := range snap.Branches { - if b.ID == "local-wip-working-tree" || strings.HasPrefix(b.ID, "local-wip-") { + if !b.HasLocal && !b.HasRemote { + if b.State == "merged" || (b.PR != nil && b.PR.ReviewState == "MERGED") { + historyOnly++ // yalnızca PR geçmişi: temizlenecek bir şey yok + } continue } - isMerged := b.State == "merged" || (b.PR != nil && b.PR.ReviewState == "MERGED") - if !isMerged && !b.OriginGone && b.State != "gone" { + if !b.Prunable || b.SuggestedCmd == "" { continue } - proof := "Uzak dal silinmiş (origin: gone)." if b.PR != nil && b.PR.ReviewState == "MERGED" { proof = fmt.Sprintf("GitHub PR #%d birleştirildi (MERGED).", b.PR.Number) - } else if isMerged { + } else if b.State == "merged" { proof = "Git geçmişinde main omurgasına birleştirilmiş (merged)." } - - cmd := b.SuggestedCmd - if cmd == "" { - if b.HasLocal { - cmd = fmt.Sprintf("git branch -D %s", b.Name) - } else if b.HasRemote { - cmd = fmt.Sprintf("git push origin --delete %s", b.Name) - } - } - - prNum := 0 - prState := "" + prNum, prState := 0, "" if b.PR != nil { - prNum = b.PR.Number - prState = b.PR.ReviewState + prNum, prState = b.PR.Number, b.PR.ReviewState } - candidates = append(candidates, cleanupCandidate{ - Name: b.Name, - HasLocal: b.HasLocal, - HasRemote: b.HasRemote, - OriginGone: b.OriginGone, - PRNumber: prNum, - PRState: prState, - Proof: proof, - SuggestedCmd: cmd, + Name: b.Name, HasLocal: b.HasLocal, HasRemote: b.HasRemote, OriginGone: b.OriginGone, + PRNumber: prNum, PRState: prState, Proof: proof, SuggestedCmd: b.SuggestedCmd, }) } - mode := snap.Repo.Mode if mode == "" { mode = "live" } + summary := fmt.Sprintf("%d adet temizlenebilir birleşmiş/silinmiş dal adayı bulundu.", len(candidates)) + if len(candidates) == 0 { + summary = "Temizlenebilir dal yok." + } return map[string]any{ - "mode": mode, - "repo": snap.Repo.Name, - "count": len(candidates), - "summary": fmt.Sprintf("%d adet temizlenebilir birleşmiş/silinmiş dal adayı bulundu.", len(candidates)), - "candidates": candidates, - "note": "MCP üzerinden hiçbir dal doğrudan silinmez. Temizlemek için 'suggestedCmd' komutunu terminalde çalıştırabilir veya GitArc UI üzerindeki 'Temizle' butonunu kullanabilirsiniz.", + "mode": mode, + "repo": snap.Repo.Name, + "count": len(candidates), + "summary": summary, + "candidates": candidates, + "historyOnlyIgnored": historyOnly, + "note": "MCP üzerinden hiçbir dal doğrudan silinmez. Temizlemek için 'suggestedCmd' komutunu terminalde çalıştırabilir veya GitArc UI üzerindeki 'Temizle' butonunu kullanabilirsiniz. Uzun ömürlü dallar (develop, release/*) ve yalnızca PR geçmişinde kalan adlar aday sayılmaz.", } } diff --git a/internal/model/model.go b/internal/model/model.go index 0f7840a..d38c141 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -324,6 +324,8 @@ type ActionLogEntry struct { // RepoID: kaydın oluştuğu proje. Günlük proje başına gösterilir (bir projenin hatası ötekinin günlüğünde görünmesin); // boş (eski kayıtlar) her projede görünür, böylece hiçbir şey kaybolmaz. RepoID string `json:"repoId,omitempty"` + // RepoName: yalnızca denetim günlüğü (MCP gitarc_audit_log) okunurken doldurulur; saklanmaz. + RepoName string `json:"repoName,omitempty"` } // SyncStep, bir veri toplama adımının (git fetch, gh PR listesi, koruma sorgusu) son durumudur. diff --git a/internal/model/protection.go b/internal/model/protection.go index 3e894b6..319308e 100644 --- a/internal/model/protection.go +++ b/internal/model/protection.go @@ -28,7 +28,9 @@ type ProtectionPlan struct { Profile string `json:"profile"` // "temel" | "ci" | "siki" // State: "none" (korumasız) | "active" (klasik koruma var) | "ruleset" (Ruleset ile korunuyor, GitArc dokunmaz) // | "unknown" (okunamadı / yetki yok) | "unsupported" (planda dal koruması yok) - State string `json:"state"` + State string `json:"state"` + // Source: Current'ın nereden okunduğu: "classic" (klasik dal koruması) | "ruleset" (dala uygulanan GitHub Ruleset kuralları, SALT OKUNUR) | "". + Source string `json:"source,omitempty"` Applicable bool `json:"applicable"` Current ProtectionSettings `json:"current"` Target ProtectionSettings `json:"target"`