diff --git a/REFACTOR_INDEX.md b/REFACTOR_INDEX.md new file mode 100644 index 0000000..b73f5b6 --- /dev/null +++ b/REFACTOR_INDEX.md @@ -0,0 +1,69 @@ +# GitArc Mimari ve Refaktör Takip İndeksi (Refactor Index) + +Bu belge, GitArc projesinin kod tabanı sağlığını, modül sınırlarını, tespit edilen tekrarları ve refaktör ilerlemesini takip etmek amacıyla tutulur. + +--- + +## 📊 1. Mevcut Kod Boyutları ve Durum Haritası + +| Katman | Dosya | Satır | Sorumluluk | Durum / Hedef | +|---|---|---|---|---| +| **Web Frontend** | `web/app.js` | 3.470 | Monolitik UI/SVG/State/Inspector/Modal orkestratörü | 🚨 **Modüler ES6 Modüllerine bölünecek** (Hedef: ~200 satır ana giriş) | +| **Web Frontend** | `web/fallback.js` | 672 | Tarayıcı çevrimdışı (offline) simülasyon motoru | ✅ İyi durumda (Tri-Mode parity korunuyor) | +| **Web Frontend** | `web/tasarim.css` | 2.931 | Tasarım sistemi, tema, PocketUI, animasyonlar | ✅ Düzenli, Strict CSP uyumlu | +| **Go Engine** | `internal/gitengine/simulation.go` | 1.423 | In-memory simülasyon repo yöneticisi | ✅ `simulation_enterprise_mock.go` (523 satır) ayrıldı | +| **Go Engine** | `internal/gitengine/simulation_enterprise_mock.go` | 523 | MegaCorp 50 geliştirici demo simülasyon veri yükü | ✅ Temiz ayrıldı | +| **Go Engine** | `internal/gitengine/collector.go` | 1.200 | Yerel Git komutları (`git log`, `merge-tree`, `for-each-ref`) | ✅ `collector_github.go` ayrıldı | +| **Go Engine** | `internal/gitengine/collector_github.go` | 334 | GitHub CLI/API metadata, PR listeleri ve ruleset kontrolleri | ✅ Temiz ayrıldı | +| **Go Engine** | `internal/gitengine/conflict_studio.go` | 714 | İzole 3-yollu çakışma stüdyosu ve motoru | ✅ İyi durumda | +| **Go Engine** | `internal/gitengine/live_mutations.go` | 584 | Canlı Git/GitHub mutasyonları | ✅ İyi durumda | +| **Go Engine** | `internal/gitengine/diagnostics.go` | 403 | Ters indeks Cross-PR ve CI log regex parser | ✅ İyi durumda | +| **Go Engine** | `internal/gitengine/proposals.go` | 280 | AI commit/PR teklif stüdyosu | ✅ İyi durumda | +| **Go Engine** | `internal/gitengine/guard_config.go` | 264 | Güvenlik kalkanı ve secret engelleme kuralları | ✅ İyi durumda | +| **Go Engine** | `internal/gitengine/projects.go` | 233 | Kalıcı proje yönetimi (`projects.json`) | ✅ İyi durumda | +| **Go Engine** | `internal/gitengine/lanes.go` | 99 | Interval packing şerit yerleşim algoritması | ✅ Kompakt ve odaklı | +| **Go MCP** | `internal/mcp/server.go` | 897 | Sıfır bağımlılıklı JSON-RPC 2.0 MCP sunucusu | ✅ Canlı `activeContext` entegreli | +| **Go HTTP/API** | `main.go` | 674 | HTTP router, güvenlik middleware'leri, CLI bayrakları | ✅ Temiz ve güvenli | + +--- + +## 🔍 2. Tespit Edilen Tekrarlar (Code Duplications) ve İyileştirme Alanları + +### A. Go Motoru Tarafı +1. **GitHub Metadata & Yerel Git Ayrımı (`collector.go`):** + - Yerel Git komutları (`git log`, `git merge-tree`, `git for-each-ref`) ile harici GitHub CLI (`gh pr list`, `gh api`) kodları aynı dosyada iç içe geçmiş durumda. + - **Çözüm:** GitHub sorguları `collector_github.go` dosyasına taşınacak. +2. **Enterprise Simülasyon Veri Yükü (`simulation.go`):** + - 50 kişilik geliştirici kadrosu, 16 commit düğümü ve 12 dal mock verisi `simulation.go` dosyasının %27'sini kaplıyor. + - **Çözüm:** `simulation_enterprise_mock.go` içine alınacak. +3. **Mükerrer CLI/Komut Çalıştırıcıları:** + - `runCmd` fonksiyonu ve zaman aşımı kalıpları kontrol edilip standartlaştırılacak. + +### B. JavaScript / Web Arayüzü Tarafı +1. **Monolitik `app.js` Yapısı:** + - Tek dosyada 3.470 satır kod bulunuyor. SVG koordinat hesaplamaları, Inspector DOM oluşturucuları, modal kontrolleri ve REST istekleri iç içe. +2. **Kopya HTML Kart Şablonları:** + - Eylem butonları (`🎯 Dala Geç`, `🧹 Sil / Temizle`, `🚀 Push & PR`) hem SVG içinde (`buildCapsuleForeignObject`), hem sağ Inspector'da (`renderInspector`), hem de Bottom Dock radar kartlarında benzer biçimde tekrar ediyor. +3. **Planlanan Modüler Yapı (Vanilla ES Modules - Sıfır Dış Bağımlılık):** + - `web/modules/state.js` -> Global durum, reaktif seçimler, snapshot cache + - `web/modules/api.js` -> `/api/*` REST uç noktaları ve hata yönetimi + - `web/modules/canvas.js` -> SVG omurga, paraboller, bezier eğrileri, zoom/pan + - `web/modules/inspector.js` -> Sağ panel (Inspector) kartları ve form işleyicileri + - `web/modules/dock.js` -> PocketUI alt çekmece, radar ve log akışı + - `web/modules/modals.js` -> Çakışma stüdyosu, proje yöneticisi ve kokpit turu + - `web/modules/utils.js` -> `esc`, `truncate`, zaman formatlama, DOM yardımcıları + - `web/app.js` -> Ana orkestratör (~150 satır) + +--- + +## 📋 3. Refaktör İlerleme Takip Listesi + +- [x] **Adım 0:** Refaktör Envanter İndeksinin Kurulması (`REFACTOR_INDEX.md`) +- [x] **Adım 1:** Go - `simulation.go` içinden `buildEnterpriseSimulation` -> `simulation_enterprise_mock.go` ayrımı +- [x] **Adım 2:** Go - `collector.go` içinden GitHub CLI/API fonksiyonları -> `collector_github.go` ayrımı +- [x] **Adım 3:** Go testlerinin ve binary derlemesinin doğrulanması (`go test -v ./... && go build`) (25/25 PASS) +- [ ] **Adım 4:** JS - `web/modules/utils.js` ve `web/modules/state.js` / `api.js` temel altyapısının kurulması +- [ ] **Adım 5:** JS - `web/modules/canvas.js` (SVG render motoru) ayrımı +- [ ] **Adım 6:** JS - `web/modules/inspector.js` ve `web/modules/dock.js` ayrımı +- [ ] **Adım 7:** JS - `web/modules/modals.js` ayrımı +- [ ] **Adım 8:** `TestWebAssetsStrictCSPCompliance` ve tam sistem entegrasyon doğrulaması diff --git a/internal/gitengine/collector.go b/internal/gitengine/collector.go index 0f0194a..d41ab6f 100644 --- a/internal/gitengine/collector.go +++ b/internal/gitengine/collector.go @@ -3,7 +3,6 @@ package gitengine import ( "bytes" "context" - "encoding/json" "fmt" "os" "os/exec" @@ -20,19 +19,9 @@ import ( const ( // AppVersion identifies the current GitArc release embedded at build time. AppVersion = "0.8.0" - ghCacheTTL = 10 * time.Second maxActiveBranches = 40 ) -type ghCacheEntry struct { - fetchedAt time.Time - openPRs map[string]model.PRStatus - mergedPRs map[string]model.PRStatus - mergedArches []model.BranchArc - branchProtected bool - protectionSummary string -} - type cachedBranchEval struct { mergeBaseSHA string aheadMain int @@ -42,26 +31,16 @@ type cachedBranchEval struct { } var ( - ghCacheMu sync.Mutex - ghCache = map[string]ghCacheEntry{} evalCacheMu sync.RWMutex evalCache = map[string]cachedBranchEval{} ) -// InvalidateGHCache clears cached GitHub PR / Actions metadata for repoPath. -func InvalidateGHCache(repoPath string) { - ghCacheMu.Lock() - delete(ghCache, filepath.Clean(repoPath)) - ghCacheMu.Unlock() -} - var ( reMergeTreeConflict = regexp.MustCompile(`CONFLICT\s*\([^)]+\):\s*Merge conflict in\s+(.+)$`) reMergePRSubject = regexp.MustCompile(`Merge pull request #(\d+) from [^/\s]+/([^\s]+)`) reMergeBranchSubj = regexp.MustCompile(`Merge branch '([^']+)'`) reTrackAhead = regexp.MustCompile(`ahead (\d+)`) reTrackBehind = regexp.MustCompile(`behind (\d+)`) - reActionsRunID = regexp.MustCompile(`/actions/runs/(\d+)`) ) // parseUpstreamTrack parses git %(upstream:track) values such as @@ -79,14 +58,6 @@ func parseUpstreamTrack(track string) (ahead, behind int, gone bool) { return ahead, behind, gone } -// extractRunIDFromURL extracts the GitHub Actions run ID from a check detailsUrl. -func extractRunIDFromURL(detailsURL string) string { - if m := reActionsRunID.FindStringSubmatch(detailsURL); len(m) == 2 { - return m[1] - } - return "" -} - // ParseMergeTreeOutput inspects the stdout/stderr of `git merge-tree --write-tree` // and builds a ConflictDetail without touching the working directory. func ParseMergeTreeOutput(exitCode int, output string) *model.ConflictDetail { @@ -468,291 +439,6 @@ func extractMergedArchesFromSpine(ctx context.Context, repoPath, defaultBranch s return arches } -type ghPRPayload struct { - Number int `json:"number"` - HeadRefName string `json:"headRefName"` - Title string `json:"title"` - Body string `json:"body"` - ReviewDecision string `json:"reviewDecision"` - URL string `json:"url"` - Author struct { - Login string `json:"login"` - } `json:"author"` - StatusCheckRollup []struct { - Name string `json:"name"` - Context string `json:"context"` - Status string `json:"status"` - State string `json:"state"` - Conclusion string `json:"conclusion"` - DetailsURL string `json:"detailsUrl"` - TargetURL string `json:"targetUrl"` - WorkflowName string `json:"workflowName"` - } `json:"statusCheckRollup"` -} - -func fetchGHMetadataCached(ctx context.Context, repoPath, remoteName, defaultBranch string, nodes []model.CommitNode, shaToIdx map[string]int, existing []model.BranchArc) (map[string]model.PRStatus, map[string]model.PRStatus, []model.BranchArc, bool, string) { - key := filepath.Clean(repoPath) - ghCacheMu.Lock() - cached, ok := ghCache[key] - if ok && time.Since(cached.fetchedAt) < ghCacheTTL { - openCopy := make(map[string]model.PRStatus, len(cached.openPRs)) - for k, v := range cached.openPRs { - openCopy[k] = v - } - mergedCopy := make(map[string]model.PRStatus, len(cached.mergedPRs)) - for k, v := range cached.mergedPRs { - mergedCopy[k] = v - } - archesCopy := make([]model.BranchArc, len(cached.mergedArches)) - copy(archesCopy, cached.mergedArches) - ghCacheMu.Unlock() - return openCopy, mergedCopy, archesCopy, cached.branchProtected, cached.protectionSummary - } - ghCacheMu.Unlock() - - if urlOut, _, err := runCmd(ctx, repoPath, "git", "remote", "get-url", remoteName); err != nil || !strings.Contains(strings.ToLower(urlOut), "github.com") { - summary := "GitHub dışı uzak depo (Saf Git modu)" - ghCacheMu.Lock() - ghCache[key] = ghCacheEntry{ - fetchedAt: time.Now(), - openPRs: map[string]model.PRStatus{}, - mergedPRs: map[string]model.PRStatus{}, - protectionSummary: summary, - } - ghCacheMu.Unlock() - return map[string]model.PRStatus{}, map[string]model.PRStatus{}, nil, false, summary - } - - openPRs := fetchGHPRs(ctx, repoPath) - mergedPRs, mergedArches := fetchGHMergedPRs(ctx, repoPath, nodes, shaToIdx, existing) - branchProtected, protectionSummary := fetchGHBranchProtection(ctx, repoPath, defaultBranch) - - ghCacheMu.Lock() - ghCache[key] = ghCacheEntry{ - fetchedAt: time.Now(), - openPRs: openPRs, - mergedPRs: mergedPRs, - mergedArches: mergedArches, - branchProtected: branchProtected, - protectionSummary: protectionSummary, - } - ghCacheMu.Unlock() - - return openPRs, mergedPRs, mergedArches, branchProtected, protectionSummary -} - -func fetchGHBranchProtection(ctx context.Context, repoPath, defaultBranch string) (bool, string) { - if _, err := exec.LookPath("gh"); err != nil { - return false, "gh CLI yok; koruma okunamadı" - } - ghCtx, cancel := context.WithTimeout(ctx, 3*time.Second) - defer cancel() - - // 1. Klasik branch protection denetimi - out, _, err := runCmd(ghCtx, repoPath, "gh", "api", fmt.Sprintf("repos/:owner/:repo/branches/%s/protection", defaultBranch), "--jq", ".required_status_checks.strict") - if err == nil { - return true, fmt.Sprintf("Aktif (strict checks: %s)", strings.TrimSpace(out)) - } - - // 2. Modern GitHub Ruleset denetimi (Madde 5) - rulesetCtx, rCancel := context.WithTimeout(ctx, 3*time.Second) - defer rCancel() - rOut, _, rErr := runCmd(rulesetCtx, repoPath, "gh", "api", "repos/:owner/:repo/rulesets") - if rErr == nil && strings.TrimSpace(rOut) != "" && strings.TrimSpace(rOut) != "[]" { - type ghRulesetItem struct { - ID int `json:"id"` - Name string `json:"name"` - Target string `json:"target"` - Enforcement string `json:"enforcement"` - } - var rItems []ghRulesetItem - if json.Unmarshal([]byte(rOut), &rItems) == nil { - for _, r := range rItems { - enf := strings.ToLower(r.Enforcement) - if (enf == "active" || enf == "evaluate") && (r.Target == "" || r.Target == "branch") { - return true, fmt.Sprintf("Aktif (GitHub Ruleset: %s)", r.Name) - } - } - } - } - - low := strings.ToLower(out) - if strings.Contains(low, "upgrade to github pro") { - return false, "Korumasız (GitHub Free özel repo / Pro gerekli)" - } - return false, "Korumasız (Doğrudan push/force-push açık)" -} - -type ghMergedPRPayload struct { - Number int `json:"number"` - HeadRefName string `json:"headRefName"` - Title string `json:"title"` - Body string `json:"body"` - URL string `json:"url"` - Author struct { - Login string `json:"login"` - } `json:"author"` - MergeCommit *struct { - OID string `json:"oid"` - } `json:"mergeCommit"` -} - -func fetchGHPRs(ctx context.Context, repoPath string) map[string]model.PRStatus { - res := map[string]model.PRStatus{} - if _, err := exec.LookPath("gh"); err != nil { - return res - } - ghCtx, cancel := context.WithTimeout(ctx, 4*time.Second) - defer cancel() - out, _, err := runCmd(ghCtx, repoPath, "gh", "pr", "list", "--state", "open", "--limit", "20", - "--json", "number,headRefName,title,body,author,reviewDecision,statusCheckRollup,url") - if err != nil || strings.TrimSpace(out) == "" { - return res - } - var items []ghPRPayload - if err := json.Unmarshal([]byte(out), &items); err != nil { - return res - } - for _, it := range items { - rev := it.ReviewDecision - if rev == "" { - rev = "REVIEW_REQUIRED" - } - ciState := "SUCCESS" - if len(it.StatusCheckRollup) == 0 { - ciState = "RUNNING" - } - failedStep := "" - runID := "" - workflow := "ci.yml" - for _, chk := range it.StatusCheckRollup { - chkName := chk.Name - if chkName == "" { - chkName = chk.Context - } - if chk.WorkflowName != "" { - workflow = chk.WorkflowName - } - conc := strings.ToUpper(chk.Conclusion) - st := strings.ToUpper(chk.Status) - ctxSt := strings.ToUpper(chk.State) - if conc == "FAILURE" || conc == "TIMED_OUT" || conc == "CANCELLED" || ctxSt == "FAILURE" || ctxSt == "ERROR" { - ciState = "FAILURE" - failedStep = chkName - runID = extractRunIDFromURL(chk.DetailsURL) - if runID == "" { - runID = extractRunIDFromURL(chk.TargetURL) - } - break - } - if (st != "" && st != "COMPLETED") || ctxSt == "PENDING" { - ciState = "RUNNING" - } - } - - var rawLog string - var extracts []model.CIFailExtract - if ciState == "FAILURE" && runID != "" { - logCtx, logCancel := context.WithTimeout(ctx, 3*time.Second) - if logOut, _, err := runCmd(logCtx, repoPath, "gh", "run", "view", runID, "--log-failed"); err == nil && strings.TrimSpace(logOut) != "" { - if len(logOut) > 16000 { - logOut = logOut[len(logOut)-16000:] - } - rawLog = logOut - extracts = ExtractCILog(rawLog) - } - logCancel() - } - - res[it.HeadRefName] = model.PRStatus{ - Number: it.Number, - Title: it.Title, - Body: it.Body, - Author: it.Author.Login, - URL: it.URL, - ReviewState: rev, - CI: &model.CIStatus{ - State: ciState, - Workflow: workflow, - RunID: runID, - Duration: "—", - FailedStep: failedStep, - Extracts: extracts, - RawLog: rawLog, - }, - } - } - return res -} - -func fetchGHMergedPRs(ctx context.Context, repoPath string, nodes []model.CommitNode, shaToIdx map[string]int, existing []model.BranchArc) (map[string]model.PRStatus, []model.BranchArc) { - mergedMap := map[string]model.PRStatus{} - if _, err := exec.LookPath("gh"); err != nil { - return mergedMap, nil - } - seenMergeIdx := map[int]bool{} - for _, a := range existing { - seenMergeIdx[a.EndSpineIndex] = true - } - - ghCtx, cancel := context.WithTimeout(ctx, 4*time.Second) - defer cancel() - out, _, err := runCmd(ghCtx, repoPath, "gh", "pr", "list", "--state", "merged", "--limit", "60", - "--json", "number,headRefName,title,body,author,mergeCommit,url") - if err != nil || strings.TrimSpace(out) == "" { - return mergedMap, nil - } - var items []ghMergedPRPayload - if err := json.Unmarshal([]byte(out), &items); err != nil { - return mergedMap, nil - } - - var arches []model.BranchArc - for _, it := range items { - prObj := model.PRStatus{ - Number: it.Number, - Title: it.Title, - Body: it.Body, - Author: it.Author.Login, - URL: it.URL, - ReviewState: "MERGED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "ci.yml", Duration: "—"}, - } - if it.HeadRefName != "" { - if _, exists := mergedMap[it.HeadRefName]; !exists { - mergedMap[it.HeadRefName] = prObj - } - } - if it.MergeCommit == nil || it.MergeCommit.OID == "" { - continue - } - endIdx, ok := shaToIdx[it.MergeCommit.OID] - if !ok || seenMergeIdx[endIdx] || endIdx == 0 { - continue - } - seenMergeIdx[endIdx] = true - startIdx := endIdx - 1 - if startIdx < 0 { - startIdx = 0 - } - arches = append(arches, model.BranchArc{ - ID: fmt.Sprintf("gh-merged-%d", it.Number), - Name: it.HeadRefName, - Hemisphere: "upper", - State: "merged", - StartSpineIndex: startIdx, - EndSpineIndex: endIdx, - BaseSHA: nodes[startIdx].ShortSHA, - MergeSHA: nodes[endIdx].ShortSHA, - HasRemote: false, - RemoteRef: "", - PR: &prObj, - LastCommitMsg: it.Title, - }) - } - return mergedMap, arches -} - // BuildSuggestedCommand produces a ready-to-copy git/gh CLI chain for the branch's current state. func BuildSuggestedCommand(b model.BranchArc, defBranch string) string { if defBranch == "" { diff --git a/internal/gitengine/collector_github.go b/internal/gitengine/collector_github.go new file mode 100644 index 0000000..5667049 --- /dev/null +++ b/internal/gitengine/collector_github.go @@ -0,0 +1,334 @@ +package gitengine + +import ( + "context" + "encoding/json" + "fmt" + "os/exec" + "path/filepath" + "regexp" + "strings" + "sync" + "time" + + "gitarc/internal/model" +) + +const ghCacheTTL = 10 * time.Second + +type ghCacheEntry struct { + fetchedAt time.Time + openPRs map[string]model.PRStatus + mergedPRs map[string]model.PRStatus + mergedArches []model.BranchArc + branchProtected bool + protectionSummary string +} + +var ( + ghCacheMu sync.Mutex + ghCache = map[string]ghCacheEntry{} +) + +// InvalidateGHCache clears cached GitHub PR / Actions metadata for repoPath. +func InvalidateGHCache(repoPath string) { + ghCacheMu.Lock() + delete(ghCache, filepath.Clean(repoPath)) + ghCacheMu.Unlock() +} + +var runIDRegex = regexp.MustCompile(`/actions/runs/(\d+)`) + +// extractRunIDFromURL extracts the GitHub Actions run ID from a check detailsUrl. +func extractRunIDFromURL(detailsURL string) string { + m := runIDRegex.FindStringSubmatch(detailsURL) + if len(m) > 1 { + return m[1] + } + return "" +} + +type ghPRPayload struct { + Number int `json:"number"` + HeadRefName string `json:"headRefName"` + Title string `json:"title"` + Body string `json:"body"` + ReviewDecision string `json:"reviewDecision"` + URL string `json:"url"` + Author struct { + Login string `json:"login"` + } `json:"author"` + StatusCheckRollup []struct { + Name string `json:"name"` + Context string `json:"context"` + Status string `json:"status"` + State string `json:"state"` + Conclusion string `json:"conclusion"` + DetailsURL string `json:"detailsUrl"` + TargetURL string `json:"targetUrl"` + WorkflowName string `json:"workflowName"` + } `json:"statusCheckRollup"` +} + +type ghMergedPRPayload struct { + Number int `json:"number"` + HeadRefName string `json:"headRefName"` + Title string `json:"title"` + Body string `json:"body"` + URL string `json:"url"` + Author struct { + Login string `json:"login"` + } `json:"author"` + MergeCommit *struct { + OID string `json:"oid"` + } `json:"mergeCommit"` +} + +func fetchGHMetadataCached(ctx context.Context, repoPath, remoteName, defaultBranch string, nodes []model.CommitNode, shaToIdx map[string]int, existing []model.BranchArc) (map[string]model.PRStatus, map[string]model.PRStatus, []model.BranchArc, bool, string) { + key := filepath.Clean(repoPath) + ghCacheMu.Lock() + cached, ok := ghCache[key] + if ok && time.Since(cached.fetchedAt) < ghCacheTTL { + openCopy := make(map[string]model.PRStatus, len(cached.openPRs)) + for k, v := range cached.openPRs { + openCopy[k] = v + } + mergedCopy := make(map[string]model.PRStatus, len(cached.mergedPRs)) + for k, v := range cached.mergedPRs { + mergedCopy[k] = v + } + archesCopy := make([]model.BranchArc, len(cached.mergedArches)) + copy(archesCopy, cached.mergedArches) + ghCacheMu.Unlock() + return openCopy, mergedCopy, archesCopy, cached.branchProtected, cached.protectionSummary + } + ghCacheMu.Unlock() + + if urlOut, _, err := runCmd(ctx, repoPath, "git", "remote", "get-url", remoteName); err != nil || !strings.Contains(strings.ToLower(urlOut), "github.com") { + summary := "GitHub dışı uzak depo (Saf Git modu)" + ghCacheMu.Lock() + ghCache[key] = ghCacheEntry{ + fetchedAt: time.Now(), + openPRs: map[string]model.PRStatus{}, + mergedPRs: map[string]model.PRStatus{}, + protectionSummary: summary, + } + ghCacheMu.Unlock() + return map[string]model.PRStatus{}, map[string]model.PRStatus{}, nil, false, summary + } + + openPRs := fetchGHPRs(ctx, repoPath) + mergedPRs, mergedArches := fetchGHMergedPRs(ctx, repoPath, nodes, shaToIdx, existing) + branchProtected, protectionSummary := fetchGHBranchProtection(ctx, repoPath, defaultBranch) + + ghCacheMu.Lock() + ghCache[key] = ghCacheEntry{ + fetchedAt: time.Now(), + openPRs: openPRs, + mergedPRs: mergedPRs, + mergedArches: mergedArches, + branchProtected: branchProtected, + protectionSummary: protectionSummary, + } + ghCacheMu.Unlock() + + return openPRs, mergedPRs, mergedArches, branchProtected, protectionSummary +} + +func fetchGHBranchProtection(ctx context.Context, repoPath, defaultBranch string) (bool, string) { + if _, err := exec.LookPath("gh"); err != nil { + return false, "gh CLI yok; koruma okunamadı" + } + ghCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + + // 1. Klasik branch protection denetimi + out, _, err := runCmd(ghCtx, repoPath, "gh", "api", fmt.Sprintf("repos/:owner/:repo/branches/%s/protection", defaultBranch), "--jq", ".required_status_checks.strict") + if err == nil { + return true, fmt.Sprintf("Aktif (strict checks: %s)", strings.TrimSpace(out)) + } + + // 2. Modern GitHub Ruleset denetimi (Madde 5) + rulesetCtx, rCancel := context.WithTimeout(ctx, 3*time.Second) + defer rCancel() + rOut, _, rErr := runCmd(rulesetCtx, repoPath, "gh", "api", "repos/:owner/:repo/rulesets") + if rErr == nil && strings.TrimSpace(rOut) != "" && strings.TrimSpace(rOut) != "[]" { + type ghRulesetItem struct { + ID int `json:"id"` + Name string `json:"name"` + Target string `json:"target"` + Enforcement string `json:"enforcement"` + } + var rItems []ghRulesetItem + if json.Unmarshal([]byte(rOut), &rItems) == nil { + for _, r := range rItems { + enf := strings.ToLower(r.Enforcement) + if (enf == "active" || enf == "evaluate") && (r.Target == "" || r.Target == "branch") { + return true, fmt.Sprintf("Aktif (GitHub Ruleset: %s)", r.Name) + } + } + } + } + + low := strings.ToLower(out) + if strings.Contains(low, "upgrade to github pro") { + return false, "Korumasız (GitHub Free özel repo / Pro gerekli)" + } + return false, "Korumasız (Doğrudan push/force-push açık)" +} + +func fetchGHPRs(ctx context.Context, repoPath string) map[string]model.PRStatus { + res := map[string]model.PRStatus{} + if _, err := exec.LookPath("gh"); err != nil { + return res + } + ghCtx, cancel := context.WithTimeout(ctx, 4*time.Second) + defer cancel() + out, _, err := runCmd(ghCtx, repoPath, "gh", "pr", "list", "--state", "open", "--limit", "20", + "--json", "number,headRefName,title,body,author,reviewDecision,statusCheckRollup,url") + if err != nil || strings.TrimSpace(out) == "" { + return res + } + var items []ghPRPayload + if err := json.Unmarshal([]byte(out), &items); err != nil { + return res + } + for _, it := range items { + rev := it.ReviewDecision + if rev == "" { + rev = "REVIEW_REQUIRED" + } + ciState := "SUCCESS" + if len(it.StatusCheckRollup) == 0 { + ciState = "RUNNING" + } + failedStep := "" + runID := "" + workflow := "ci.yml" + for _, chk := range it.StatusCheckRollup { + chkName := chk.Name + if chkName == "" { + chkName = chk.Context + } + if chk.WorkflowName != "" { + workflow = chk.WorkflowName + } + conc := strings.ToUpper(chk.Conclusion) + st := strings.ToUpper(chk.Status) + ctxSt := strings.ToUpper(chk.State) + if conc == "FAILURE" || conc == "TIMED_OUT" || conc == "CANCELLED" || ctxSt == "FAILURE" || ctxSt == "ERROR" { + ciState = "FAILURE" + failedStep = chkName + runID = extractRunIDFromURL(chk.DetailsURL) + if runID == "" { + runID = extractRunIDFromURL(chk.TargetURL) + } + break + } + if (st != "" && st != "COMPLETED") || ctxSt == "PENDING" { + ciState = "RUNNING" + } + } + + var rawLog string + var extracts []model.CIFailExtract + if ciState == "FAILURE" && runID != "" { + logCtx, logCancel := context.WithTimeout(ctx, 3*time.Second) + if logOut, _, err := runCmd(logCtx, repoPath, "gh", "run", "view", runID, "--log-failed"); err == nil && strings.TrimSpace(logOut) != "" { + if len(logOut) > 16000 { + logOut = logOut[len(logOut)-16000:] + } + rawLog = logOut + extracts = ExtractCILog(rawLog) + } + logCancel() + } + + res[it.HeadRefName] = model.PRStatus{ + Number: it.Number, + Title: it.Title, + Body: it.Body, + Author: it.Author.Login, + URL: it.URL, + ReviewState: rev, + CI: &model.CIStatus{ + State: ciState, + Workflow: workflow, + RunID: runID, + Duration: "—", + FailedStep: failedStep, + Extracts: extracts, + RawLog: rawLog, + }, + } + } + return res +} + +func fetchGHMergedPRs(ctx context.Context, repoPath string, nodes []model.CommitNode, shaToIdx map[string]int, existing []model.BranchArc) (map[string]model.PRStatus, []model.BranchArc) { + mergedMap := map[string]model.PRStatus{} + if _, err := exec.LookPath("gh"); err != nil { + return mergedMap, nil + } + seenMergeIdx := map[int]bool{} + for _, a := range existing { + seenMergeIdx[a.EndSpineIndex] = true + } + + ghCtx, cancel := context.WithTimeout(ctx, 4*time.Second) + defer cancel() + out, _, err := runCmd(ghCtx, repoPath, "gh", "pr", "list", "--state", "merged", "--limit", "60", + "--json", "number,headRefName,title,body,author,mergeCommit,url") + if err != nil || strings.TrimSpace(out) == "" { + return mergedMap, nil + } + var items []ghMergedPRPayload + if err := json.Unmarshal([]byte(out), &items); err != nil { + return mergedMap, nil + } + + var arches []model.BranchArc + for _, it := range items { + prObj := model.PRStatus{ + Number: it.Number, + Title: it.Title, + Body: it.Body, + Author: it.Author.Login, + URL: it.URL, + ReviewState: "MERGED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "ci.yml", Duration: "—"}, + } + if it.HeadRefName != "" { + if _, exists := mergedMap[it.HeadRefName]; !exists { + mergedMap[it.HeadRefName] = prObj + } + } + if it.MergeCommit == nil || it.MergeCommit.OID == "" { + continue + } + endIdx, ok := shaToIdx[it.MergeCommit.OID] + if !ok || seenMergeIdx[endIdx] || endIdx == 0 { + continue + } + seenMergeIdx[endIdx] = true + startIdx := endIdx - 1 + if startIdx < 0 { + startIdx = 0 + } + arches = append(arches, model.BranchArc{ + ID: fmt.Sprintf("gh-merged-%d", it.Number), + Name: it.HeadRefName, + Hemisphere: "upper", + State: "merged", + StartSpineIndex: startIdx, + EndSpineIndex: endIdx, + BaseSHA: nodes[startIdx].ShortSHA, + MergeSHA: nodes[endIdx].ShortSHA, + HasRemote: false, + RemoteRef: "", + PR: &prObj, + LastCommitMsg: it.Title, + }) + } + return mergedMap, arches +} diff --git a/internal/gitengine/simulation.go b/internal/gitengine/simulation.go index a90d6ad..816756a 100644 --- a/internal/gitengine/simulation.go +++ b/internal/gitengine/simulation.go @@ -1321,526 +1321,6 @@ func buildSandboxSimulation() simWorkspace { } } -// buildEnterpriseSimulation creates a large-scale repository simulation representing -// an enterprise engineering organization with 4 primary tracks and 50 active developers. -func buildEnterpriseSimulation() simWorkspace { - // 50 Developers Roster: - // Alice Chen, Mehmet Yilmaz, David Kim, Elena Rostova, Carlos Silva, Sarah Jenkins, - // Kenji Sato, Fatima Zahra, Lucas Muller, Ayse Kaya, Priya Patel, Marcus Vance, - // Emily Blunt, Tarik Ozkan, Olga Ivanova, Chen Wei, Diego Torres, Anna Kowalski, - // Hassan Ali, Kevin Duque, Rachel Green, Zeynep Demir, Brian Cox, Sophie Martin, - // Alex Turner, Cem Yilmaz, Victoria Beck, Leo Messi, Elizabeth Swan, Mustafa Ak, - // John Doe, Jane Smith, Can Erik, Gita Rao, Tom Hanks, Deniz Oz, - // Charlie Brown, Selin Erdogan, Robert De, Alperen Sen, Clara Oswald, Baris Manco, - // Emma Watson, Serdar Oz, Natalie Portman, Onur Bay, Yuki Tsunoda, Burak Oz, - // Mia Wallace, Hakan Sukru. - - nodes := []model.CommitNode{ - {SHA: "a101f01", ShortSHA: "a101f01", Subject: "chore(release): cut v3.0.0 enterprise lts baseline", Author: "alice.chen", RelativeTime: "14 gün önce", SpineIndex: 0, Tag: "v3.0.0"}, - {SHA: "b202e12", ShortSHA: "b202e12", Subject: "feat(gateway): envoy proxy mesh ingress integration", Author: "david.kim", RelativeTime: "12 gün önce", SpineIndex: 1}, - {SHA: "c303d23", ShortSHA: "c303d23", Subject: "Merge PR #790 feat/distributed-cache-redis7", Author: "mehmet.yilmaz", RelativeTime: "11 gün önce", SpineIndex: 2, IsMerge: true}, - {SHA: "d404c34", ShortSHA: "d404c34", Subject: "chore(security): apply cve-2026-4190 kernel patch", Author: "elena.rostova", RelativeTime: "10 gün önce", SpineIndex: 3, Tag: "v3.1.0"}, - {SHA: "e505b45", ShortSHA: "e505b45", Subject: "Merge PR #794 fix/jwt-rsa-key-rotation", Author: "carlos.silva", RelativeTime: "9 gün önce", SpineIndex: 4, IsMerge: true}, - {SHA: "f606a56", ShortSHA: "f606a56", Subject: "feat(observability): opentelemetry trace collector", Author: "sarah.jenkins", RelativeTime: "8 gün önce", SpineIndex: 5}, - {SHA: "0707967", ShortSHA: "0707967", Subject: "Merge PR #798 chore/upgrade-go123", Author: "kenji.sato", RelativeTime: "7 gün önce", SpineIndex: 6, IsMerge: true}, - {SHA: "1808878", ShortSHA: "1808878", Subject: "chore(release): v3.2.0 platform core rollout", Author: "fatima.zahra", RelativeTime: "6 gün önce", SpineIndex: 7, Tag: "v3.2.0"}, - {SHA: "2909789", ShortSHA: "2909789", Subject: "feat(billing): multi-currency stripe webhooks handler", Author: "priya.patel", RelativeTime: "5 gün önce", SpineIndex: 8}, - {SHA: "3a0a69a", ShortSHA: "3a0a69a", Subject: "Merge PR #802 feat/kafka-event-streaming", Author: "lucas.muller", RelativeTime: "4 gün önce", SpineIndex: 9, IsMerge: true}, - {SHA: "4b0b5ab", ShortSHA: "4b0b5ab", Subject: "fix(db): postgres deadlocks on concurrent audit writes", Author: "ayse.kaya", RelativeTime: "3 gün önce", SpineIndex: 10}, - {SHA: "5c0c4bc", ShortSHA: "5c0c4bc", Subject: "Merge PR #807 perf/graphql-query-batching", Author: "marcus.vance", RelativeTime: "2 gün önce", SpineIndex: 11, IsMerge: true}, - {SHA: "6d0d3cd", ShortSHA: "6d0d3cd", Subject: "feat(auth): webauthn passkey biometric authentication", Author: "emily.blunt", RelativeTime: "1 gün önce", SpineIndex: 12}, - {SHA: "7e0e2de", ShortSHA: "7e0e2de", Subject: "Merge PR #810 fix/k8s-pod-disruption-budget", Author: "tarik.ozkan", RelativeTime: "18 saat önce", SpineIndex: 13, IsMerge: true, Tag: "v3.3.0-rc2"}, - {SHA: "8f0f1ef", ShortSHA: "8f0f1ef", Subject: "chore(config): bump production cluster replicas to 64", Author: "olga.ivanova", RelativeTime: "8 saat önce", SpineIndex: 14}, - {SHA: "90100f0", ShortSHA: "90100f0", Subject: "ci(security): enforce codeql & gitleaks scanner", Author: "chen.wei", RelativeTime: "2 saat önce", SpineIndex: 15, IsHEAD: true}, - } - - entCiFailLog := `2026-11-17T06:14:02.100Z ##[group]Testing service mesh tracing spans -2026-11-17T06:14:04.300Z === RUN TestDistributedTracePropagation -2026-11-17T06:14:05.120Z --- PASS: TestDistributedTracePropagation (0.82s) -2026-11-17T06:14:05.121Z === RUN TestOpenTelemetrySpanExporter -2026-11-17T06:14:07.450Z exporter_test.go:88: context deadline exceeded after 2000ms waiting for OTLP gRPC endpoint: 10.240.12.9:4317 -2026-11-17T06:14:07.452Z --- FAIL: TestOpenTelemetrySpanExporter (2.33s) -2026-11-17T06:14:07.455Z === RUN TestSpanPanicRecovery -2026-11-17T06:14:07.460Z panic: nil pointer dereference evaluating spanContext.TraceFlags() -2026-11-17T06:14:07.461Z goroutine 148 [running]: -2026-11-17T06:14:07.462Z platform/internal/telemetry.ExportSpan(...) -2026-11-17T06:14:07.463Z services/telemetry/exporter.go:142 +0x2a8 -2026-11-17T06:14:07.470Z FAIL platform/services/telemetry 3.150s -2026-11-17T06:14:07.480Z ##[error]Process completed with exit code 1.` - - entConflictPreview := `<<<<<< HEAD (main @ 8f0f1ef) -replicas: 64 -minReplicas: 16 -autoscaling: - targetCPUUtilizationPercentage: 70 - targetMemoryUtilizationPercentage: 75 -====== -replicas: 32 -minReplicas: 8 -autoscaling: - targetCPUUtilizationPercentage: 80 - targetMemoryUtilizationPercentage: 85 ->>>>>> origin/feat/auth-v2-jwt-rotation - -[git merge-tree --write-tree] Otomatik Çözüm Önerisi: -⚠ Çakışan dosya: deploy/helm/values.yaml (Üretim küme autoscaling eşikleri)` - - branches := []model.BranchArc{ - // 1. DÖRT ANA DAL (Primary Long-Running Tracks) - // Track 1: develop (Ana geliştirme entegrasyon dalı) - { - ID: "br-track-develop", - Name: "develop", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 10, - EndSpineIndex: 15, - BaseSHA: "4b0b5ab", - HasRemote: true, - RemoteRef: "origin/develop", - PR: &model.PRStatus{ - Number: 770, - Title: "track(develop): active platform integration line", - Author: "diego.torres", - ReviewState: "APPROVED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "Nightly Integration Test", Duration: "4m 12s"}, - }, - HasLocal: true, - LocalSHA: "fa0192b", - Author: "diego.torres", - AheadMain: 5, - BehindMain: 1, - UncommittedCount: 0, - LastCommitMsg: "develop: sync nightly service builds across all clusters", - ChangedFiles: []string{"services/develop-manifest.yaml"}, - }, - // Track 2: staging (Ön-canlı doğrulama dalı) - { - ID: "br-track-staging", - Name: "staging", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 12, - EndSpineIndex: 15, - BaseSHA: "6d0d3cd", - HasRemote: true, - RemoteRef: "origin/staging", - PR: &model.PRStatus{ - Number: 775, - Title: "track(staging): pre-production validation track", - Author: "anna.kowalski", - ReviewState: "APPROVED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "E2E Smoke Tests", Duration: "3m 45s"}, - }, - HasLocal: true, - LocalSHA: "fb1283c", - Author: "anna.kowalski", - AheadMain: 3, - BehindMain: 0, - UncommittedCount: 0, - LastCommitMsg: "staging: promote RC candidates to stg-us-east-2 cluster", - ChangedFiles: []string{"deploy/staging/kustomization.yaml"}, - }, - // Track 3: release/v3.3 (Sürüm hazırlık dalı) - { - ID: "br-track-release-33", - Name: "release/v3.3", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 13, - EndSpineIndex: 15, - BaseSHA: "7e0e2de", - HasRemote: true, - RemoteRef: "origin/release/v3.3", - PR: &model.PRStatus{ - Number: 780, - Title: "track(release): v3.3.0 stabilization and release gate", - Author: "hassan.ali", - ReviewState: "REVIEW_REQUIRED", - CI: &model.CIStatus{State: "RUNNING", Workflow: "Release Candidate Sanity", Duration: "1m 15s"}, - }, - HasLocal: true, - LocalSHA: "fc2374d", - Author: "hassan.ali", - AheadMain: 2, - BehindMain: 0, - UncommittedCount: 0, - LastCommitMsg: "release: lock dependency freeze for v3.3.0 final tag", - ChangedFiles: []string{"VERSION", "CHANGELOG.md"}, - }, - // Track 4: support/lts-2.x (Uzun vadeli destek dalı) - { - ID: "br-track-lts-2x", - Name: "support/lts-2.x", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 0, - EndSpineIndex: 7, - BaseSHA: "a101f01", - HasRemote: true, - RemoteRef: "origin/support/lts-2.x", - PR: &model.PRStatus{ - Number: 750, - Title: "track(lts): long-term maintenance branch for 2.x customers", - Author: "kevin.duque", - ReviewState: "APPROVED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "LTS Security Regression", Duration: "5m 20s"}, - }, - HasLocal: false, - Author: "kevin.duque", - AheadMain: 6, - BehindMain: 8, - UncommittedCount: 0, - LastCommitMsg: "lts: backport openssl vulnerability fix to 2.8 patchline", - ChangedFiles: []string{"crypto/openssl_compat.c"}, - }, - - // 2. GELİŞTİRİCİ DALLARI VE PR'LARI (50 Developer Contributions) - // Merged Pull Requests (Geçmiş başarılar) - { - ID: "br-ent-merged-802", - Name: "feat/kafka-event-streaming", - Hemisphere: "upper", - State: "merged", - StartSpineIndex: 7, - EndSpineIndex: 9, - BaseSHA: "1808878", - MergeSHA: "3a0a69a", - HasRemote: true, - RemoteRef: "origin/feat/kafka-event-streaming", - PR: &model.PRStatus{ - Number: 802, - Title: "feat(events): partitioned kafka message broker with zookeeper-less kraft", - Author: "alice.chen", - ReviewState: "MERGED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "Broker Load Test", Duration: "2m 45s"}, - }, - HasLocal: false, - Author: "alice.chen", - LastCommitMsg: "kafka: add producer ack retry with exponential backoff", - ChangedFiles: []string{"services/events/kafka.go"}, - }, - { - ID: "br-ent-merged-807", - Name: "perf/graphql-query-batching", - Hemisphere: "upper", - State: "merged", - StartSpineIndex: 9, - EndSpineIndex: 11, - BaseSHA: "3a0a69a", - MergeSHA: "5c0c4bc", - HasRemote: true, - RemoteRef: "origin/perf/graphql-query-batching", - PR: &model.PRStatus{ - Number: 807, - Title: "perf(graphql): dataloader N+1 batch caching across microservices", - Author: "lucas.muller", - ReviewState: "MERGED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "GraphQL Benchmark", Duration: "1m 55s"}, - }, - HasLocal: false, - Author: "lucas.muller", - LastCommitMsg: "graphql: reduce redis roundtrips using bulk dataloader", - ChangedFiles: []string{"gateway/graphql/batcher.go"}, - }, - - // Açık PR'lar (CI: RUNNING - Nabız animasyonlu) - { - ID: "br-ent-open-815", - Name: "feat/grpc-service-mesh", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 11, - EndSpineIndex: 14, - BaseSHA: "5c0c4bc", - HasRemote: true, - RemoteRef: "origin/feat/grpc-service-mesh", - PR: &model.PRStatus{ - Number: 815, - Title: "feat(mesh): http/2 multiplexing and mTLS mutual authentication", - Author: "david.kim", - ReviewState: "REVIEW_REQUIRED", - CI: &model.CIStatus{ - State: "RUNNING", - Workflow: "mTLS Certificate Exchange Suite", - Duration: "0m 42s", - }, - }, - HasLocal: true, - LocalSHA: "ea1109a", - Author: "david.kim", - AheadMain: 3, - BehindMain: 1, - UncommittedCount: 0, - LastCommitMsg: "mesh: establish strict mTLS boundary on ingress", - ChangedFiles: []string{"services/mesh/tls.go", "deploy/helm/values.yaml"}, - }, - { - ID: "br-ent-open-818", - Name: "feat/billing-stripe-webhooks", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 12, - EndSpineIndex: 15, - BaseSHA: "6d0d3cd", - HasRemote: true, - RemoteRef: "origin/feat/billing-stripe-webhooks", - PR: &model.PRStatus{ - Number: 818, - Title: "feat(billing): idempotency keys for payment intent hooks", - Author: "priya.patel", - ReviewState: "REVIEW_REQUIRED", - CI: &model.CIStatus{ - State: "RUNNING", - Workflow: "Payment Gateway Simulation", - Duration: "0m 22s", - }, - }, - HasLocal: false, - Author: "priya.patel", - AheadMain: 2, - BehindMain: 0, - UncommittedCount: 0, - LastCommitMsg: "billing: lock transaction table during webhook replay", - ChangedFiles: []string{"services/billing/stripe.go"}, - }, - - // Açık PR (CI: FAILURE - Kırmızı uyarı, log çıkarma ve panik analizi) - { - ID: "br-ent-open-820", - Name: "fix/distributed-tracing-span", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 10, - EndSpineIndex: 14, - BaseSHA: "4b0b5ab", - HasRemote: true, - RemoteRef: "origin/fix/distributed-tracing-span", - PR: &model.PRStatus{ - Number: 820, - Title: "fix(telemetry): eliminate nil dereference in otel span export", - Author: "mehmet.yilmaz", - ReviewState: "CHANGES_REQUESTED", - CI: &model.CIStatus{ - State: "FAILURE", - Workflow: "OpenTelemetry Integration CI", - RunID: "994182410", - Duration: "0m 58s", - FailedStep: "Testing service mesh tracing spans", - RawLog: entCiFailLog, - }, - }, - HasLocal: true, - LocalSHA: "eb2210b", - Author: "mehmet.yilmaz", - IsHEAD: true, - AheadMain: 4, - BehindMain: 2, - UncommittedCount: 3, - LastCommitMsg: "telemetry: check nil span context before flag evaluation", - ChangedFiles: []string{"services/telemetry/exporter.go", "services/telemetry/exporter_test.go"}, - }, - - // Açık PR (ÇAKIŞMA VE CROSS-PR COLLISION: Auth ve Helm dosyaları) - { - ID: "br-ent-open-825", - Name: "feat/auth-v2-jwt-rotation", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 11, - EndSpineIndex: 15, - BaseSHA: "5c0c4bc", - HasRemote: true, - RemoteRef: "origin/feat/auth-v2-jwt-rotation", - PR: &model.PRStatus{ - Number: 825, - Title: "feat(auth): dynamic asymmetric jwt rotation with jwks endpoint", - Author: "elena.rostova", - ReviewState: "APPROVED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "Security & Auth Test", Duration: "1m 30s"}, - }, - HasLocal: true, - LocalSHA: "ec3321c", - Author: "elena.rostova", - AheadMain: 3, - BehindMain: 1, - UncommittedCount: 0, - LastCommitMsg: "auth: rotate public jwks keys every 6 hours", - ChangedFiles: []string{"services/auth/jwt.go", "api/v1/auth.go", "deploy/helm/values.yaml"}, - Conflict: &model.ConflictDetail{ - HasConflict: true, - Files: []string{"deploy/helm/values.yaml"}, - IsChangelogOrLock: false, - Strategy: "merge-editor", - PreviewUnified: entConflictPreview, - }, - }, - { - ID: "br-ent-open-828", - Name: "feat/oauth-pkce-flow", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 12, - EndSpineIndex: 15, - BaseSHA: "6d0d3cd", - HasRemote: true, - RemoteRef: "origin/feat/oauth-pkce-flow", - PR: &model.PRStatus{ - Number: 828, - Title: "feat(oauth): pkce challenge verification for native mobile apps", - Author: "carlos.silva", - ReviewState: "REVIEW_REQUIRED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "OAuth Conformance Suite", Duration: "1m 18s"}, - }, - HasLocal: false, - Author: "carlos.silva", - AheadMain: 2, - BehindMain: 0, - UncommittedCount: 0, - LastCommitMsg: "oauth: verify sha256 code challenge on token exchange", - ChangedFiles: []string{"api/v1/auth.go", "services/auth/pkce.go"}, // Cross-PR collision with 825! - }, - - // Açık PR (Onaylı ve Hazır) - { - ID: "br-ent-open-830", - Name: "fix/postgres-connection-leak", - Hemisphere: "upper", - State: "open", - StartSpineIndex: 13, - EndSpineIndex: 15, - BaseSHA: "7e0e2de", - HasRemote: true, - RemoteRef: "origin/fix/postgres-connection-leak", - PR: &model.PRStatus{ - Number: 830, - Title: "fix(database): defer pgxpool.Conn.Release on error paths", - Author: "ayse.kaya", - ReviewState: "APPROVED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "Postgres Stress Benchmark", Duration: "2m 10s"}, - }, - HasLocal: false, - Author: "ayse.kaya", - AheadMain: 1, - BehindMain: 0, - UncommittedCount: 0, - LastCommitMsg: "db: guarantee connection release in batch execution loops", - ChangedFiles: []string{"storage/postgres/pool.go"}, - }, - - // 3. KALINTI VE YEREL DALLAR (Remnants, Fresh Local & WIP) - // Squash Remnant / Local Remnant (origin: gone, aheadMain > 0) - { - ID: "br-ent-remnant-gone", - Name: "feat/legacy-elasticsearch-drop", - Hemisphere: "upper", - State: "merged", - StartSpineIndex: 8, - EndSpineIndex: 11, - BaseSHA: "2909789", - MergeSHA: "5c0c4bc", - HasRemote: false, - RemoteRef: "origin/feat/legacy-elasticsearch-drop", - OriginGone: true, - PR: &model.PRStatus{ - Number: 795, - Title: "refactor(search): migrate query cluster from es7 to opensearch", - Author: "marcus.vance", - ReviewState: "MERGED", - CI: &model.CIStatus{State: "SUCCESS", Workflow: "Search Ingestion Tests", Duration: "3m 05s"}, - }, - HasLocal: true, - LocalSHA: "5c0c4bc", - Author: "marcus.vance", - AheadMain: 3, - LastCommitMsg: "search: deprecate old elasticsearch index clients", - ChangedFiles: []string{"services/search/client.go"}, - }, - - // Taze Yerel Dal (🌱 Yeni Yerel Dal, aheadMain == 0, remote yok) - { - ID: "br-ent-fresh-local", - Name: "feat/edge-wasm-worker", - Hemisphere: "lower", - State: "open", - StartSpineIndex: 15, - EndSpineIndex: 16, - BaseSHA: "90100f0", - HasRemote: false, - HasLocal: true, - LocalSHA: "90100f0", - Author: "rachel.green", - IsHEAD: false, - AheadMain: 0, - BehindMain: 0, - UncommittedCount: 0, - LastCommitMsg: "edge: bootstrap webassembly micro-worker scaffolding", - ChangedFiles: []string{"workers/wasm/worker.go"}, - }, - - // Alt Ray Yerel WIP ve Deney Dalları (Lower Hemisphere) - { - ID: "br-ent-local-ebpf", - Name: "wip/ebpf-tc-bandwidth-shaper", - Hemisphere: "lower", - State: "open", - StartSpineIndex: 13, - EndSpineIndex: 15, - BaseSHA: "7e0e2de", - HasRemote: false, - HasLocal: true, - LocalSHA: "ed4432d", - Author: "tarik.ozkan", - IsHEAD: false, - AheadMain: 2, - BehindMain: 0, - UncommittedCount: 5, - LastCommitMsg: "wip(ebpf): attach tc ingress filter to veth pairs for rate limiting", - ChangedFiles: []string{"kernel/bpf/shaper.c", "kernel/bpf/loader.go"}, - }, - { - ID: "br-ent-local-wasm", - Name: "exp/v8-isolated-sandbox", - Hemisphere: "lower", - State: "open", - StartSpineIndex: 14, - EndSpineIndex: 16, - BaseSHA: "8f0f1ef", - HasRemote: false, - HasLocal: true, - LocalSHA: "ee5543e", - Author: "olga.ivanova", - IsHEAD: false, - AheadMain: 1, - BehindMain: 0, - UncommittedCount: 2, - LastCommitMsg: "exp(sandbox): evaluate v8 isolate heap snapshot limits", - ChangedFiles: []string{"runtime/v8/isolate.cc"}, - }, - } - - return simWorkspace{ - repo: model.RepoMeta{ - ID: "sim-enterprise", - Name: "MegaCorp Cloud Platform (50 Geliştirici)", - Path: "(Enterprise Çoklu Dal Simülasyonu)", - DefaultBranch: "main", - RemoteName: "origin", - Ahead: 3, - Behind: 0, - DirtyCount: 3, - Mode: "simulation", - VersionTag: "v3.3.0-rc2", - CurrentUser: "mehmet.yilmaz", - BranchProtected: true, - ProtectionSummary: "Korumalı (PR Zorunlu + 2 Onay + Strict CI + Force-Push Kilitli)", - AppVersion: AppVersion, - }, - nodes: nodes, - branches: branches, - } -} - // CheckForUpdates inspects remote git tags to detect whether a newer GitArc release exists. func (m *Manager) CheckForUpdates() (map[string]any, error) { latest := AppVersion diff --git a/internal/gitengine/simulation_enterprise_mock.go b/internal/gitengine/simulation_enterprise_mock.go new file mode 100644 index 0000000..f3aa8fb --- /dev/null +++ b/internal/gitengine/simulation_enterprise_mock.go @@ -0,0 +1,523 @@ +package gitengine + +import "gitarc/internal/model" + +// buildEnterpriseSimulation creates a large-scale repository simulation representing +// an enterprise engineering organization with 4 primary tracks and 50 active developers. +func buildEnterpriseSimulation() simWorkspace { + // 50 Developers Roster: + // Alice Chen, Mehmet Yilmaz, David Kim, Elena Rostova, Carlos Silva, Sarah Jenkins, + // Kenji Sato, Fatima Zahra, Lucas Muller, Ayse Kaya, Priya Patel, Marcus Vance, + // Emily Blunt, Tarik Ozkan, Olga Ivanova, Chen Wei, Diego Torres, Anna Kowalski, + // Hassan Ali, Kevin Duque, Rachel Green, Zeynep Demir, Brian Cox, Sophie Martin, + // Alex Turner, Cem Yilmaz, Victoria Beck, Leo Messi, Elizabeth Swan, Mustafa Ak, + // John Doe, Jane Smith, Can Erik, Gita Rao, Tom Hanks, Deniz Oz, + // Charlie Brown, Selin Erdogan, Robert De, Alperen Sen, Clara Oswald, Baris Manco, + // Emma Watson, Serdar Oz, Natalie Portman, Onur Bay, Yuki Tsunoda, Burak Oz, + // Mia Wallace, Hakan Sukru. + + nodes := []model.CommitNode{ + {SHA: "a101f01", ShortSHA: "a101f01", Subject: "chore(release): cut v3.0.0 enterprise lts baseline", Author: "alice.chen", RelativeTime: "14 gün önce", SpineIndex: 0, Tag: "v3.0.0"}, + {SHA: "b202e12", ShortSHA: "b202e12", Subject: "feat(gateway): envoy proxy mesh ingress integration", Author: "david.kim", RelativeTime: "12 gün önce", SpineIndex: 1}, + {SHA: "c303d23", ShortSHA: "c303d23", Subject: "Merge PR #790 feat/distributed-cache-redis7", Author: "mehmet.yilmaz", RelativeTime: "11 gün önce", SpineIndex: 2, IsMerge: true}, + {SHA: "d404c34", ShortSHA: "d404c34", Subject: "chore(security): apply cve-2026-4190 kernel patch", Author: "elena.rostova", RelativeTime: "10 gün önce", SpineIndex: 3, Tag: "v3.1.0"}, + {SHA: "e505b45", ShortSHA: "e505b45", Subject: "Merge PR #794 fix/jwt-rsa-key-rotation", Author: "carlos.silva", RelativeTime: "9 gün önce", SpineIndex: 4, IsMerge: true}, + {SHA: "f606a56", ShortSHA: "f606a56", Subject: "feat(observability): opentelemetry trace collector", Author: "sarah.jenkins", RelativeTime: "8 gün önce", SpineIndex: 5}, + {SHA: "0707967", ShortSHA: "0707967", Subject: "Merge PR #798 chore/upgrade-go123", Author: "kenji.sato", RelativeTime: "7 gün önce", SpineIndex: 6, IsMerge: true}, + {SHA: "1808878", ShortSHA: "1808878", Subject: "chore(release): v3.2.0 platform core rollout", Author: "fatima.zahra", RelativeTime: "6 gün önce", SpineIndex: 7, Tag: "v3.2.0"}, + {SHA: "2909789", ShortSHA: "2909789", Subject: "feat(billing): multi-currency stripe webhooks handler", Author: "priya.patel", RelativeTime: "5 gün önce", SpineIndex: 8}, + {SHA: "3a0a69a", ShortSHA: "3a0a69a", Subject: "Merge PR #802 feat/kafka-event-streaming", Author: "lucas.muller", RelativeTime: "4 gün önce", SpineIndex: 9, IsMerge: true}, + {SHA: "4b0b5ab", ShortSHA: "4b0b5ab", Subject: "fix(db): postgres deadlocks on concurrent audit writes", Author: "ayse.kaya", RelativeTime: "3 gün önce", SpineIndex: 10}, + {SHA: "5c0c4bc", ShortSHA: "5c0c4bc", Subject: "Merge PR #807 perf/graphql-query-batching", Author: "marcus.vance", RelativeTime: "2 gün önce", SpineIndex: 11, IsMerge: true}, + {SHA: "6d0d3cd", ShortSHA: "6d0d3cd", Subject: "feat(auth): webauthn passkey biometric authentication", Author: "emily.blunt", RelativeTime: "1 gün önce", SpineIndex: 12}, + {SHA: "7e0e2de", ShortSHA: "7e0e2de", Subject: "Merge PR #810 fix/k8s-pod-disruption-budget", Author: "tarik.ozkan", RelativeTime: "18 saat önce", SpineIndex: 13, IsMerge: true, Tag: "v3.3.0-rc2"}, + {SHA: "8f0f1ef", ShortSHA: "8f0f1ef", Subject: "chore(config): bump production cluster replicas to 64", Author: "olga.ivanova", RelativeTime: "8 saat önce", SpineIndex: 14}, + {SHA: "90100f0", ShortSHA: "90100f0", Subject: "ci(security): enforce codeql & gitleaks scanner", Author: "chen.wei", RelativeTime: "2 saat önce", SpineIndex: 15, IsHEAD: true}, + } + + entCiFailLog := `2026-11-17T06:14:02.100Z ##[group]Testing service mesh tracing spans +2026-11-17T06:14:04.300Z === RUN TestDistributedTracePropagation +2026-11-17T06:14:05.120Z --- PASS: TestDistributedTracePropagation (0.82s) +2026-11-17T06:14:05.121Z === RUN TestOpenTelemetrySpanExporter +2026-11-17T06:14:07.450Z exporter_test.go:88: context deadline exceeded after 2000ms waiting for OTLP gRPC endpoint: 10.240.12.9:4317 +2026-11-17T06:14:07.452Z --- FAIL: TestOpenTelemetrySpanExporter (2.33s) +2026-11-17T06:14:07.455Z === RUN TestSpanPanicRecovery +2026-11-17T06:14:07.460Z panic: nil pointer dereference evaluating spanContext.TraceFlags() +2026-11-17T06:14:07.461Z goroutine 148 [running]: +2026-11-17T06:14:07.462Z platform/internal/telemetry.ExportSpan(...) +2026-11-17T06:14:07.463Z services/telemetry/exporter.go:142 +0x2a8 +2026-11-17T06:14:07.470Z FAIL platform/services/telemetry 3.150s +2026-11-17T06:14:07.480Z ##[error]Process completed with exit code 1.` + + entConflictPreview := `<<<<<< HEAD (main @ 8f0f1ef) +replicas: 64 +minReplicas: 16 +autoscaling: + targetCPUUtilizationPercentage: 70 + targetMemoryUtilizationPercentage: 75 +====== +replicas: 32 +minReplicas: 8 +autoscaling: + targetCPUUtilizationPercentage: 80 + targetMemoryUtilizationPercentage: 85 +>>>>>> origin/feat/auth-v2-jwt-rotation + +[git merge-tree --write-tree] Otomatik Çözüm Önerisi: +⚠ Çakışan dosya: deploy/helm/values.yaml (Üretim küme autoscaling eşikleri)` + + branches := []model.BranchArc{ + // 1. DÖRT ANA DAL (Primary Long-Running Tracks) + // Track 1: develop (Ana geliştirme entegrasyon dalı) + { + ID: "br-track-develop", + Name: "develop", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 10, + EndSpineIndex: 15, + BaseSHA: "4b0b5ab", + HasRemote: true, + RemoteRef: "origin/develop", + PR: &model.PRStatus{ + Number: 770, + Title: "track(develop): active platform integration line", + Author: "diego.torres", + ReviewState: "APPROVED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "Nightly Integration Test", Duration: "4m 12s"}, + }, + HasLocal: true, + LocalSHA: "fa0192b", + Author: "diego.torres", + AheadMain: 5, + BehindMain: 1, + UncommittedCount: 0, + LastCommitMsg: "develop: sync nightly service builds across all clusters", + ChangedFiles: []string{"services/develop-manifest.yaml"}, + }, + // Track 2: staging (Ön-canlı doğrulama dalı) + { + ID: "br-track-staging", + Name: "staging", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 12, + EndSpineIndex: 15, + BaseSHA: "6d0d3cd", + HasRemote: true, + RemoteRef: "origin/staging", + PR: &model.PRStatus{ + Number: 775, + Title: "track(staging): pre-production validation track", + Author: "anna.kowalski", + ReviewState: "APPROVED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "E2E Smoke Tests", Duration: "3m 45s"}, + }, + HasLocal: true, + LocalSHA: "fb1283c", + Author: "anna.kowalski", + AheadMain: 3, + BehindMain: 0, + UncommittedCount: 0, + LastCommitMsg: "staging: promote RC candidates to stg-us-east-2 cluster", + ChangedFiles: []string{"deploy/staging/kustomization.yaml"}, + }, + // Track 3: release/v3.3 (Sürüm hazırlık dalı) + { + ID: "br-track-release-33", + Name: "release/v3.3", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 13, + EndSpineIndex: 15, + BaseSHA: "7e0e2de", + HasRemote: true, + RemoteRef: "origin/release/v3.3", + PR: &model.PRStatus{ + Number: 780, + Title: "track(release): v3.3.0 stabilization and release gate", + Author: "hassan.ali", + ReviewState: "REVIEW_REQUIRED", + CI: &model.CIStatus{State: "RUNNING", Workflow: "Release Candidate Sanity", Duration: "1m 15s"}, + }, + HasLocal: true, + LocalSHA: "fc2374d", + Author: "hassan.ali", + AheadMain: 2, + BehindMain: 0, + UncommittedCount: 0, + LastCommitMsg: "release: lock dependency freeze for v3.3.0 final tag", + ChangedFiles: []string{"VERSION", "CHANGELOG.md"}, + }, + // Track 4: support/lts-2.x (Uzun vadeli destek dalı) + { + ID: "br-track-lts-2x", + Name: "support/lts-2.x", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 0, + EndSpineIndex: 7, + BaseSHA: "a101f01", + HasRemote: true, + RemoteRef: "origin/support/lts-2.x", + PR: &model.PRStatus{ + Number: 750, + Title: "track(lts): long-term maintenance branch for 2.x customers", + Author: "kevin.duque", + ReviewState: "APPROVED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "LTS Security Regression", Duration: "5m 20s"}, + }, + HasLocal: false, + Author: "kevin.duque", + AheadMain: 6, + BehindMain: 8, + UncommittedCount: 0, + LastCommitMsg: "lts: backport openssl vulnerability fix to 2.8 patchline", + ChangedFiles: []string{"crypto/openssl_compat.c"}, + }, + + // 2. GELİŞTİRİCİ DALLARI VE PR'LARI (50 Developer Contributions) + // Merged Pull Requests (Geçmiş başarılar) + { + ID: "br-ent-merged-802", + Name: "feat/kafka-event-streaming", + Hemisphere: "upper", + State: "merged", + StartSpineIndex: 7, + EndSpineIndex: 9, + BaseSHA: "1808878", + MergeSHA: "3a0a69a", + HasRemote: true, + RemoteRef: "origin/feat/kafka-event-streaming", + PR: &model.PRStatus{ + Number: 802, + Title: "feat(events): partitioned kafka message broker with zookeeper-less kraft", + Author: "alice.chen", + ReviewState: "MERGED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "Broker Load Test", Duration: "2m 45s"}, + }, + HasLocal: false, + Author: "alice.chen", + LastCommitMsg: "kafka: add producer ack retry with exponential backoff", + ChangedFiles: []string{"services/events/kafka.go"}, + }, + { + ID: "br-ent-merged-807", + Name: "perf/graphql-query-batching", + Hemisphere: "upper", + State: "merged", + StartSpineIndex: 9, + EndSpineIndex: 11, + BaseSHA: "3a0a69a", + MergeSHA: "5c0c4bc", + HasRemote: true, + RemoteRef: "origin/perf/graphql-query-batching", + PR: &model.PRStatus{ + Number: 807, + Title: "perf(graphql): dataloader N+1 batch caching across microservices", + Author: "lucas.muller", + ReviewState: "MERGED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "GraphQL Benchmark", Duration: "1m 55s"}, + }, + HasLocal: false, + Author: "lucas.muller", + LastCommitMsg: "graphql: reduce redis roundtrips using bulk dataloader", + ChangedFiles: []string{"gateway/graphql/batcher.go"}, + }, + + // Açık PR'lar (CI: RUNNING - Nabız animasyonlu) + { + ID: "br-ent-open-815", + Name: "feat/grpc-service-mesh", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 11, + EndSpineIndex: 14, + BaseSHA: "5c0c4bc", + HasRemote: true, + RemoteRef: "origin/feat/grpc-service-mesh", + PR: &model.PRStatus{ + Number: 815, + Title: "feat(mesh): http/2 multiplexing and mTLS mutual authentication", + Author: "david.kim", + ReviewState: "REVIEW_REQUIRED", + CI: &model.CIStatus{ + State: "RUNNING", + Workflow: "mTLS Certificate Exchange Suite", + Duration: "0m 42s", + }, + }, + HasLocal: true, + LocalSHA: "ea1109a", + Author: "david.kim", + AheadMain: 3, + BehindMain: 1, + UncommittedCount: 0, + LastCommitMsg: "mesh: establish strict mTLS boundary on ingress", + ChangedFiles: []string{"services/mesh/tls.go", "deploy/helm/values.yaml"}, + }, + { + ID: "br-ent-open-818", + Name: "feat/billing-stripe-webhooks", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 12, + EndSpineIndex: 15, + BaseSHA: "6d0d3cd", + HasRemote: true, + RemoteRef: "origin/feat/billing-stripe-webhooks", + PR: &model.PRStatus{ + Number: 818, + Title: "feat(billing): idempotency keys for payment intent hooks", + Author: "priya.patel", + ReviewState: "REVIEW_REQUIRED", + CI: &model.CIStatus{ + State: "RUNNING", + Workflow: "Payment Gateway Simulation", + Duration: "0m 22s", + }, + }, + HasLocal: false, + Author: "priya.patel", + AheadMain: 2, + BehindMain: 0, + UncommittedCount: 0, + LastCommitMsg: "billing: lock transaction table during webhook replay", + ChangedFiles: []string{"services/billing/stripe.go"}, + }, + + // Açık PR (CI: FAILURE - Kırmızı uyarı, log çıkarma ve panik analizi) + { + ID: "br-ent-open-820", + Name: "fix/distributed-tracing-span", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 10, + EndSpineIndex: 14, + BaseSHA: "4b0b5ab", + HasRemote: true, + RemoteRef: "origin/fix/distributed-tracing-span", + PR: &model.PRStatus{ + Number: 820, + Title: "fix(telemetry): eliminate nil dereference in otel span export", + Author: "mehmet.yilmaz", + ReviewState: "CHANGES_REQUESTED", + CI: &model.CIStatus{ + State: "FAILURE", + Workflow: "OpenTelemetry Integration CI", + RunID: "994182410", + Duration: "0m 58s", + FailedStep: "Testing service mesh tracing spans", + RawLog: entCiFailLog, + }, + }, + HasLocal: true, + LocalSHA: "eb2210b", + Author: "mehmet.yilmaz", + IsHEAD: true, + AheadMain: 4, + BehindMain: 2, + UncommittedCount: 3, + LastCommitMsg: "telemetry: check nil span context before flag evaluation", + ChangedFiles: []string{"services/telemetry/exporter.go", "services/telemetry/exporter_test.go"}, + }, + + // Açık PR (ÇAKIŞMA VE CROSS-PR COLLISION: Auth ve Helm dosyaları) + { + ID: "br-ent-open-825", + Name: "feat/auth-v2-jwt-rotation", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 11, + EndSpineIndex: 15, + BaseSHA: "5c0c4bc", + HasRemote: true, + RemoteRef: "origin/feat/auth-v2-jwt-rotation", + PR: &model.PRStatus{ + Number: 825, + Title: "feat(auth): dynamic asymmetric jwt rotation with jwks endpoint", + Author: "elena.rostova", + ReviewState: "APPROVED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "Security & Auth Test", Duration: "1m 30s"}, + }, + HasLocal: true, + LocalSHA: "ec3321c", + Author: "elena.rostova", + AheadMain: 3, + BehindMain: 1, + UncommittedCount: 0, + LastCommitMsg: "auth: rotate public jwks keys every 6 hours", + ChangedFiles: []string{"services/auth/jwt.go", "api/v1/auth.go", "deploy/helm/values.yaml"}, + Conflict: &model.ConflictDetail{ + HasConflict: true, + Files: []string{"deploy/helm/values.yaml"}, + IsChangelogOrLock: false, + Strategy: "merge-editor", + PreviewUnified: entConflictPreview, + }, + }, + { + ID: "br-ent-open-828", + Name: "feat/oauth-pkce-flow", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 12, + EndSpineIndex: 15, + BaseSHA: "6d0d3cd", + HasRemote: true, + RemoteRef: "origin/feat/oauth-pkce-flow", + PR: &model.PRStatus{ + Number: 828, + Title: "feat(oauth): pkce challenge verification for native mobile apps", + Author: "carlos.silva", + ReviewState: "REVIEW_REQUIRED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "OAuth Conformance Suite", Duration: "1m 18s"}, + }, + HasLocal: false, + Author: "carlos.silva", + AheadMain: 2, + BehindMain: 0, + UncommittedCount: 0, + LastCommitMsg: "oauth: verify sha256 code challenge on token exchange", + ChangedFiles: []string{"api/v1/auth.go", "services/auth/pkce.go"}, // Cross-PR collision with 825! + }, + + // Açık PR (Onaylı ve Hazır) + { + ID: "br-ent-open-830", + Name: "fix/postgres-connection-leak", + Hemisphere: "upper", + State: "open", + StartSpineIndex: 13, + EndSpineIndex: 15, + BaseSHA: "7e0e2de", + HasRemote: true, + RemoteRef: "origin/fix/postgres-connection-leak", + PR: &model.PRStatus{ + Number: 830, + Title: "fix(database): defer pgxpool.Conn.Release on error paths", + Author: "ayse.kaya", + ReviewState: "APPROVED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "Postgres Stress Benchmark", Duration: "2m 10s"}, + }, + HasLocal: false, + Author: "ayse.kaya", + AheadMain: 1, + BehindMain: 0, + UncommittedCount: 0, + LastCommitMsg: "db: guarantee connection release in batch execution loops", + ChangedFiles: []string{"storage/postgres/pool.go"}, + }, + + // 3. KALINTI VE YEREL DALLAR (Remnants, Fresh Local & WIP) + // Squash Remnant / Local Remnant (origin: gone, aheadMain > 0) + { + ID: "br-ent-remnant-gone", + Name: "feat/legacy-elasticsearch-drop", + Hemisphere: "upper", + State: "merged", + StartSpineIndex: 8, + EndSpineIndex: 11, + BaseSHA: "2909789", + MergeSHA: "5c0c4bc", + HasRemote: false, + RemoteRef: "origin/feat/legacy-elasticsearch-drop", + OriginGone: true, + PR: &model.PRStatus{ + Number: 795, + Title: "refactor(search): migrate query cluster from es7 to opensearch", + Author: "marcus.vance", + ReviewState: "MERGED", + CI: &model.CIStatus{State: "SUCCESS", Workflow: "Search Ingestion Tests", Duration: "3m 05s"}, + }, + HasLocal: true, + LocalSHA: "5c0c4bc", + Author: "marcus.vance", + AheadMain: 3, + LastCommitMsg: "search: deprecate old elasticsearch index clients", + ChangedFiles: []string{"services/search/client.go"}, + }, + + // Taze Yerel Dal (🌱 Yeni Yerel Dal, aheadMain == 0, remote yok) + { + ID: "br-ent-fresh-local", + Name: "feat/edge-wasm-worker", + Hemisphere: "lower", + State: "open", + StartSpineIndex: 15, + EndSpineIndex: 16, + BaseSHA: "90100f0", + HasRemote: false, + HasLocal: true, + LocalSHA: "90100f0", + Author: "rachel.green", + IsHEAD: false, + AheadMain: 0, + BehindMain: 0, + UncommittedCount: 0, + LastCommitMsg: "edge: bootstrap webassembly micro-worker scaffolding", + ChangedFiles: []string{"workers/wasm/worker.go"}, + }, + + // Alt Ray Yerel WIP ve Deney Dalları (Lower Hemisphere) + { + ID: "br-ent-local-ebpf", + Name: "wip/ebpf-tc-bandwidth-shaper", + Hemisphere: "lower", + State: "open", + StartSpineIndex: 13, + EndSpineIndex: 15, + BaseSHA: "7e0e2de", + HasRemote: false, + HasLocal: true, + LocalSHA: "ed4432d", + Author: "tarik.ozkan", + IsHEAD: false, + AheadMain: 2, + BehindMain: 0, + UncommittedCount: 5, + LastCommitMsg: "wip(ebpf): attach tc ingress filter to veth pairs for rate limiting", + ChangedFiles: []string{"kernel/bpf/shaper.c", "kernel/bpf/loader.go"}, + }, + { + ID: "br-ent-local-wasm", + Name: "exp/v8-isolated-sandbox", + Hemisphere: "lower", + State: "open", + StartSpineIndex: 14, + EndSpineIndex: 16, + BaseSHA: "8f0f1ef", + HasRemote: false, + HasLocal: true, + LocalSHA: "ee5543e", + Author: "olga.ivanova", + IsHEAD: false, + AheadMain: 1, + BehindMain: 0, + UncommittedCount: 2, + LastCommitMsg: "exp(sandbox): evaluate v8 isolate heap snapshot limits", + ChangedFiles: []string{"runtime/v8/isolate.cc"}, + }, + } + + return simWorkspace{ + repo: model.RepoMeta{ + ID: "sim-enterprise", + Name: "MegaCorp Cloud Platform (50 Geliştirici)", + Path: "(Enterprise Çoklu Dal Simülasyonu)", + DefaultBranch: "main", + RemoteName: "origin", + Ahead: 3, + Behind: 0, + DirtyCount: 3, + Mode: "simulation", + VersionTag: "v3.3.0-rc2", + CurrentUser: "mehmet.yilmaz", + BranchProtected: true, + ProtectionSummary: "Korumalı (PR Zorunlu + 2 Onay + Strict CI + Force-Push Kilitli)", + AppVersion: AppVersion, + }, + nodes: nodes, + branches: branches, + } +} diff --git a/web/modules/api.js b/web/modules/api.js new file mode 100644 index 0000000..1587f96 --- /dev/null +++ b/web/modules/api.js @@ -0,0 +1,25 @@ +// web/modules/api.js - Unified REST API client with offline LocalFallbackEngine support +import { state } from './state.js'; + +export async function apiCall(path, method = 'GET', body = null) { + if (state.offlineMode || window.location.protocol === 'file:') { + throw new Error('offline'); + } + const opts = { + method, + headers: { + 'X-Requested-With': 'gitarc', + }, + credentials: 'same-origin', + }; + if (body !== null) { + opts.headers['Content-Type'] = 'application/json'; + opts.body = JSON.stringify(body); + } + const resp = await fetch(path, opts); + const data = await resp.json().catch(() => ({})); + if (!resp.ok) { + throw new Error(data.error || `HTTP ${resp.status}`); + } + return data; +} diff --git a/web/modules/canvas.js b/web/modules/canvas.js new file mode 100644 index 0000000..db6b0f5 --- /dev/null +++ b/web/modules/canvas.js @@ -0,0 +1,756 @@ +// web/modules/canvas.js - Parabolic SVG Canvas, Topology Geometry and Capsule Renderer +import { state, el } from './state.js'; +import { + SVG_NS, XHTML_NS, MAIN_Y, SPINE_START_X, SPINE_STEP_X, + LANE_BASE_OFFSET, LANE_STEP_Y, FO_W, FO_H, MERGED_FO_W, MERGED_FO_H, + OPEN_CAPSULE_MIN_GAP_X +} from './constants.js'; +import { + esc, truncate, svgEl, isMergedOrGone, isOpenPR, isLocalOpen, isMyBranch +} from './utils.js'; + +export function xOfSpine(idx) { + return SPINE_START_X + idx * SPINE_STEP_X; +} + +export function yOfLane(hemisphere, lane, isMerged = false) { + const l = Math.max(1, lane || 1); + const offset = isMerged ? (84 + (l - 1) * 56) : (LANE_BASE_OFFSET + (l - 1) * LANE_STEP_Y); + return hemisphere === 'lower' ? MAIN_Y + offset : MAIN_Y - offset; +} + +export function layoutOpenApexPositions(branches) { + const map = new Map(); + const lastMergedEndX = branches + .filter((b) => b.state === 'merged') + .reduce((acc, b) => Math.max(acc, xOfSpine(Math.max(b.startSpineIndex + 1, b.endSpineIndex))), 0); + + ['upper', 'lower'].forEach((hemi) => { + const openList = branches + .filter((b) => b.state !== 'merged' && b.hemisphere === hemi) + .sort((a, b) => a.startSpineIndex - b.startSpineIndex || a.endSpineIndex - b.endSpineIndex || a.name.localeCompare(b.name)); + + let prevX = -Infinity; + openList.forEach((b) => { + const startX = xOfSpine(b.startSpineIndex); + const baseX = Math.max(startX + 150, xOfSpine(Math.max(b.startSpineIndex + 1, b.endSpineIndex)) - 10); + const minClearX = hemi === 'upper' && lastMergedEndX > 0 ? Math.max(baseX, lastMergedEndX + 20) : baseX; + const apexX = prevX === -Infinity ? minClearX : Math.max(minClearX, prevX + OPEN_CAPSULE_MIN_GAP_X); + const apexY = hemi === 'lower' ? MAIN_Y + LANE_BASE_OFFSET : MAIN_Y - LANE_BASE_OFFSET; + prevX = apexX; + map.set(b.id, { apexX, apexY }); + }); + }); + return map; +} + +export function computeBranchGeometry(b, tipXOverride = null, tipYOverride = null, apexLayout = null) { + const startX = xOfSpine(b.startSpineIndex); + const isMerged = b.state === 'merged'; + const laneY = yOfLane(b.hemisphere, b.lane, isMerged); + + if (isMerged && tipXOverride === null) { + const endX = xOfSpine(Math.max(b.startSpineIndex + 1, b.endSpineIndex)); + const apexX = (startX + endX) / 2; + const apexY = laneY; + const cp1X = startX + (apexX - startX) * 0.55; + const cp2X = apexX + (endX - apexX) * 0.45; + const openD = `M ${startX} ${MAIN_Y} C ${cp1X} ${MAIN_Y}, ${cp1X} ${apexY}, ${apexX} ${apexY}`; + const closeD = `M ${apexX} ${apexY} C ${cp2X} ${apexY}, ${cp2X} ${MAIN_Y}, ${endX} ${MAIN_Y}`; + const areaD = `${openD} C ${cp2X} ${apexY}, ${cp2X} ${MAIN_Y}, ${endX} ${MAIN_Y} Z`; + return { startX, endX, apexX, apexY, openD, closeD, areaD }; + } + + const laid = apexLayout?.get(b.id); + const defaultApexX = laid ? laid.apexX : Math.max(startX + 150, xOfSpine(Math.max(b.startSpineIndex + 1, b.endSpineIndex)) - 10); + const defaultApexY = laid ? laid.apexY : laneY; + const apexX = tipXOverride !== null ? tipXOverride : defaultApexX; + const apexY = tipYOverride !== null ? tipYOverride : defaultApexY; + const cp1X = startX + (apexX - startX) * 0.55; + const openD = `M ${startX} ${MAIN_Y} C ${cp1X} ${MAIN_Y}, ${cp1X} ${apexY}, ${apexX} ${apexY}`; + return { startX, endX: null, apexX, apexY, openD, closeD: null, areaD: null }; +} + +export function branchToneClass(b) { + if (b.pr?.ci?.state === 'FAILURE') return 'ci-fail'; + if (b.conflict?.hasConflict && !b.conflict.resolved) return 'conflict'; + if (b.pr?.ci?.state === 'RUNNING') return 'ci-running'; + if (b.state === 'merged') return 'merged'; + if (b.originGone || b.state === 'gone') return 'gone'; + return b.hemisphere === 'lower' ? 'lower-open' : 'upper-open'; +} + +export function branchStrokeColor(b) { + if (b.pr?.ci?.state === 'FAILURE') return '#f85149'; + if (b.conflict?.hasConflict && !b.conflict.resolved) return '#d29922'; + if (b.pr?.ci?.state === 'RUNNING') return '#e3b341'; + if (b.state === 'merged') return '#3fb950'; + if (b.originGone || b.state === 'gone') return '#8b949e'; + return b.hemisphere === 'lower' ? '#bc8cff' : '#58a6ff'; +} + +export function matchesFilter(b) { + const q = (state.pathLens || '').trim().toLowerCase(); + if (q) { + const nameHit = (b.name || '').toLowerCase().includes(q); + const fileHit = (b.changedFiles || []).some((f) => f.toLowerCase().includes(q)); + if (!nameHit && !fileHit) return false; + } + switch (state.filter) { + case 'mine': + return Boolean(b.state === 'open' && !isMergedOrGone(b) && isMyBranch(b, state.snapshot?.repo?.currentUser)); + case 'lower': + return isLocalOpen(b); + case 'dirty': + return Boolean(b.isHead && ((b.uncommittedCount || 0) > 0 || (state.snapshot?.repo?.dirtyCount || 0) > 0)); + case 'issues': + return Boolean(b.state === 'open' && !isMergedOrGone(b) && ((b.conflict?.hasConflict && !b.conflict.resolved) || (b.crossPr && b.crossPr.length))); + case 'ci_fail': + return Boolean(b.state === 'open' && b.pr?.ci?.state === 'FAILURE'); + case 'gone': + return isMergedOrGone(b); + default: + return true; + } +} + +export function renderKPIs(onFilterChange = null) { + const branches = state.snapshot?.branches || []; + const localBranches = branches.filter((b) => b.hasLocal && !b.id.startsWith('gh-merged-') && b.id !== 'local-wip-working-tree'); + const localCount = localBranches.length; + const mergedPRCount = branches.filter((b) => b.id.startsWith('gh-merged-') || (b.state === 'merged' && !b.hasLocal)).length; + const dirtyCount = state.snapshot?.repo?.dirtyCount || branches.find((b) => b.isHead)?.uncommittedCount || 0; + + const upperCount = branches.filter(isOpenPR).length; + const lowerCount = branches.filter(isLocalOpen).length; + const mineCount = branches.filter((b) => b.state === 'open' && !isMergedOrGone(b) && isMyBranch(b, state.snapshot?.repo?.currentUser)).length; + const conflictCount = branches.filter((b) => b.state === 'open' && !isMergedOrGone(b) && ((b.conflict?.hasConflict && !b.conflict.resolved) || (b.crossPr && b.crossPr.length > 0))).length; + const failCount = branches.filter((b) => b.state === 'open' && b.pr?.ci?.state === 'FAILURE').length; + const goneCount = branches.filter(isMergedOrGone).length; + + const allTitle = `Tümü (${branches.length} düğüm):\n• ${localCount} yerel dal (klasik 'git branch' sayısı)\n• ${mergedPRCount} GitHub birleşmiş PR parabolü\n• ${branches.length - localCount - mergedPRCount} diğer uzak/sanal dal.`; + + const defs = [ + { key: 'all', label: 'Tümü', val: branches.length, tone: '', title: allTitle }, + { key: 'mine', label: '👤 Benim Dallarım (@me)', val: mineCount, tone: mineCount ? 'accent' : '', title: 'Giriş yapan kullanıcıya ait açık dallar' }, + { key: 'lower', label: 'Alt Ray (Local)', val: lowerCount, tone: lowerCount ? 'purple' : '', title: 'PR açılmamış açık yerel dallar' }, + { key: 'dirty', label: 'Değişiklik (Dirty)', val: dirtyCount, tone: dirtyCount ? 'warn' : '', title: `Çalışma ağacında ${dirtyCount} adet kaydedilmemiş dosya var.` }, + { key: 'issues', label: 'Çakışma / Cross-PR', val: conflictCount, tone: conflictCount ? 'warn' : '', title: 'Çakışan veya aynı dosyaları değiştiren açık dallar' }, + { key: 'ci_fail', label: 'CI Hatası', val: failCount, tone: failCount ? 'danger' : '', title: 'CI testleri başarısız olan dallar' }, + { key: 'gone', label: 'Birleşmiş / Gone', val: goneCount, tone: goneCount ? 'ok' : '', title: 'Main ile birleşmiş veya uzaktaki dalı silinmiş temizleme adayları' }, + ]; + + if (!el.kpiPills) return; + el.kpiPills.innerHTML = ''; + defs.forEach((d) => { + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = `kpi-pill ${d.tone} ${state.filter === d.key ? 'active' : ''}`; + if (d.title) btn.title = d.title; + btn.innerHTML = `${esc(d.label)}${d.val}`; + btn.addEventListener('click', () => { + state.filter = d.key; + renderKPIs(onFilterChange); + if (onFilterChange) onFilterChange(); + }); + el.kpiPills.appendChild(btn); + }); + + const prBadge = document.createElement('span'); + prBadge.className = `kpi-pill ${upperCount ? 'accent' : ''}`; + prBadge.title = "GitHub üzerinde açık olan Pull Request'ler"; + prBadge.innerHTML = `Üst Ray (PR)${upperCount}`; + el.kpiPills.appendChild(prBadge); + + if (el.dragHint) { + el.dragHint.innerHTML = `💡 Tümü Sayacı (${branches.length}): ${localCount} yerel dal + ${mergedPRCount} birleşmiş PR parabolüdür.`; + } +} + +export function renderTopbar(callbacks = {}) { + const snap = state.snapshot; + if (!snap) return; + + const liveLabel = state.offlineMode ? 'Offline Simülasyon' : (snap.repo.mode === 'live' ? 'Canlı Git · Aktif' : 'Simülasyon · Etkileşimli'); + if (el.modeBadge) el.modeBadge.textContent = `${snap.repo.name} · ${liveLabel}`; + if (el.engineStatus) el.engineStatus.textContent = snap.repo.mode === 'live' ? '● Canlı Repo Bağlı' : '● Simülasyon Hazır'; + + if (el.repoSelect) { + el.repoSelect.innerHTML = ''; + (snap.repos || []).forEach((r) => { + const opt = document.createElement('option'); + opt.value = r.id; + opt.textContent = r.name; + if (r.id === snap.repo.id) opt.selected = true; + el.repoSelect.appendChild(opt); + }); + } + + if (el.btnRemoveProject) el.btnRemoveProject.hidden = snap.repo.mode !== 'live'; + const cleanableCount = (snap.branches || []).filter((b) => b.originGone || b.state === 'gone' || (b.state === 'merged' && b.hasLocal)).length; + if (el.pruneCount) el.pruneCount.textContent = String(cleanableCount); + + const btnPrune = document.getElementById('btn-prune-gone'); + if (btnPrune) btnPrune.disabled = cleanableCount === 0 && snap.repo.mode !== 'live'; + const btnSync = document.getElementById('btn-sync-spine'); + if (btnSync) btnSync.disabled = snap.repo.mode !== 'live' && snap.repo.ahead === 0 && snap.repo.behind === 0; + const btnReset = document.getElementById('btn-reset-sim'); + if (btnReset) btnReset.hidden = snap.repo.mode === 'live'; + + const isProtected = Boolean(snap.repo.branchProtected); + if (el.btnProtectBranch) { + el.btnProtectBranch.textContent = isProtected ? '🛡️ main Korumalı' : '🔓 Korumasız'; + el.btnProtectBranch.className = `btn ${isProtected ? 'ok' : 'warn'}`; + } + + const verTxt = `v${snap.repo.appVersion || '0.8.0'}`; + const teamTag = snap.repo.teamMode ? ' · TEAM' : ''; + const updTag = snap.repo.updateAvailable ? ' ⬆ Güncelle' : ''; + if (el.btnUpdateCheck) { + el.btnUpdateCheck.textContent = verTxt + teamTag + updTag; + el.btnUpdateCheck.className = `btn mono ${snap.repo.updateAvailable ? 'warn' : 'ghost'}`; + } + + if (el.perfCacheBadge) el.perfCacheBadge.textContent = `⚡ ${snap.repo.cacheHits || 0} SHA hit`; + + const ahead = snap.repo.ahead || 0; + const behind = snap.repo.behind || 0; + const remoteName = snap.repo.remoteName || 'origin'; + const defBranch = snap.repo.defaultBranch || 'main'; + if (el.spineSyncBadge) { + if (ahead === 0 && behind === 0) { + el.spineSyncBadge.textContent = `${defBranch} ↔ ${remoteName}/${defBranch} (Synced)`; + el.spineSyncBadge.classList.remove('skewed'); + } else { + el.spineSyncBadge.textContent = `${defBranch} ↔ ${remoteName}/${defBranch} ↑${ahead} · ↓${behind}`; + el.spineSyncBadge.classList.add('skewed'); + } + } +} + +export function capsulePositionForApex(b, apexX, apexY) { + if (b.state === 'merged') { + return { + x: apexX - MERGED_FO_W / 2, + y: apexY - MERGED_FO_H - 6, + }; + } + const x = apexX - FO_W / 2; + const y = b.hemisphere === 'lower' ? apexY + 14 : apexY - FO_H + 12; + return { x, y }; +} + +export function buildCapsuleForeignObject(b, geom, isSelected, visible, tone, callbacks = {}) { + const { onSelectBranch, onCheckoutBranch, onMergeBranch, onPromoteBranch, onDeleteBranch, onOpenConflictStudio } = callbacks; + const snap = state.snapshot; + const isMerged = b.state === 'merged'; + const pos = capsulePositionForApex(b, geom.apexX, geom.apexY); + const fo = svgEl('foreignObject', { + x: pos.x, + y: pos.y, + width: isMerged ? MERGED_FO_W : FO_W, + height: isMerged ? MERGED_FO_H : FO_H, + class: `fo-capsule ${visible ? '' : 'dimmed'}`, + 'data-branch-id': b.id, + }); + + if (isMerged) { + const pill = document.createElementNS(XHTML_NS, 'div'); + const hasLocalLeftover = Boolean(b.originGone || b.hasLocal); + pill.className = `cap-merged-pill ${isSelected ? 'selected' : ''} ${hasLocalLeftover ? 'gone' : ''}`; + const prTxt = b.pr ? `#${b.pr.number} ` : ''; + const localTagHtml = hasLocalLeftover + ? `${b.isHead ? 'HEAD·Local' : '💻 Local'}` + : ''; + const delBtnHtml = hasLocalLeftover + ? '' + : ''; + pill.innerHTML = ` + ✓ ${esc(prTxt + truncate(b.name, hasLocalLeftover ? 11 : 19))} + ${localTagHtml} + ${delBtnHtml} + `; + pill.querySelector('button[data-act="delete"]')?.addEventListener('pointerdown', (ev) => ev.stopPropagation()); + pill.querySelector('button[data-act="delete"]')?.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onDeleteBranch) onDeleteBranch(b.id); + }); + pill.addEventListener('pointerdown', (ev) => ev.stopPropagation()); + pill.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onSelectBranch) onSelectBranch(b.id); + }); + fo.appendChild(pill); + return fo; + } + + const isLower = b.hemisphere === 'lower'; + const isWorkingTreeWip = b.id === 'local-wip-working-tree' || b.id.startsWith('local-wip-') || b.name === 'wip/working-tree'; + const isFailed = b.pr?.ci?.state === 'FAILURE'; + const isRunning = b.pr?.ci?.state === 'RUNNING'; + const isQueued = Boolean(state.pendingAutoMerge[b.id]); + const hasConflict = Boolean(b.conflict?.hasConflict && !b.conflict.resolved); + const isRemoteOnly = !b.hasLocal && b.hasRemote && b.state === 'open'; + const delTitle = isRemoteOnly ? 'PR Kapat & Uzak Dalı Sil' : 'Dalı Sil'; + + let badgeTone = 'sky'; + let badgePulse = false; + let badgeText = b.pr ? `PR #${b.pr.number} · ${b.pr.reviewState}` : 'Remote Ray'; + const isFreshLocal = isLower && !isWorkingTreeWip && b.aheadMain === 0; + const isSyncedLocal = isLower && !isWorkingTreeWip && b.aheadMain === 0 && (b.uncommittedCount || 0) === 0; + if (isFailed) { + badgeTone = 'danger'; + badgeText = `PR #${b.pr.number} · CI Failed`; + } else if (hasConflict) { + badgeTone = 'warn'; + badgeText = b.pr ? `PR #${b.pr.number} · Çakışma` : 'Merge Çakışması'; + } else if (isRunning) { + badgeTone = 'warn'; + badgePulse = true; + badgeText = `PR #${b.pr.number} · CI Çalışıyor`; + } else if (b.originGone || b.state === 'gone') { + badgeTone = 'warn'; + badgeText = 'origin: gone'; + } else if (isLower) { + badgeTone = 'purple'; + if (isWorkingTreeWip) { + badgeText = 'Yerel Taslak · Uncommitted'; + } else if (isSyncedLocal) { + badgeText = '✓ main ile Senkronize'; + } else if (isFreshLocal) { + badgeText = '🌱 Yeni Yerel Dal'; + } else { + badgeText = 'Yarım Parabol · Local'; + } + } + + const subText = isWorkingTreeWip + ? `${b.uncommittedCount || 0} dosya bekliyor · İncelemek için tıklayın` + : (isSyncedLocal + ? 'main omurgasıyla eşitlendi · Yeni commit veya değişiklik yok' + : (isFreshLocal + ? 'main omurgasında taze dal · İlk commitinizi bekliyor' + : (b.lastCommitMsg ? b.lastCommitMsg : (isLower ? `↑${b.aheadMain || 0} yerel · ${b.uncommittedCount || 0} dirty` : `↑${b.aheadMain || 0} ↓${b.behindMain || 0}`)))); + + const card = document.createElementNS(XHTML_NS, 'div'); + card.className = `cap-card ${tone} ${isSelected ? 'selected' : ''}`; + + let alertsHtml = ''; + if (isRemoteOnly) { + alertsHtml += '☁ Sadece Origin'; + } + if (hasConflict) { + alertsHtml += `${b.conflict.isChangelogOrLock ? '⚠ CHANGELOG / Lock' : '⚠ Conflict'}`; + } + if (b.crossPr?.length) { + alertsHtml += `⇄ Cross-PR ${b.crossPr.map((c) => '#' + (c.otherPrNumber || '?')).join(',')}`; + } + + const checkoutTitle = isRemoteOnly ? 'Yerelde İndir & Geç (git switch --track)' : 'Bu dala geç (git switch)'; + const checkoutBtn = (!b.isHead && !isWorkingTreeWip) + ? `` + : ''; + + let actionRowHtml = ''; + if (isFailed) { + actionRowHtml = ` + + ${checkoutBtn} + + `; + } else if (hasConflict) { + actionRowHtml = ` + + ${checkoutBtn} + + `; + } else if (isLower) { + if (isWorkingTreeWip) { + if (snap?.pendingProposal) { + actionRowHtml = ``; + } else { + actionRowHtml = ``; + } + } else { + const hasOpenPR = Boolean(b.pr && b.pr.number > 0 && b.pr.reviewState !== 'MERGED'); + const isSynced = b.aheadMain === 0 && (b.uncommittedCount || 0) === 0; + if (isSynced) { + actionRowHtml = ` + ${b.isHead ? '' : checkoutBtn} + + `; + } else { + actionRowHtml = ` + + ${hasOpenPR ? `` : ''} + ${checkoutBtn} + + `; + } + } + } else if (isRunning) { + actionRowHtml = ` + + ${checkoutBtn} + + `; + } else { + actionRowHtml = ` + + ${checkoutBtn} + + `; + } + + card.innerHTML = ` +
${esc(suggestedCmd)}
+
+ ${esc(prop.diffStat)}
+ İncelemek için bir parabol eğrisine, commit düğümüne veya radar uyarısına tıklayın.
+İpucu: Üst raydaki açık PR'lar uzaktaki dalları, alt raydaki mor eğriler yerel dalları temsil eder.
+${esc(b.conflict.previewUnified || '')}
+ ${!resolved ? `` : ''}
+ ${esc(localRunOut || b.pr.ci.rawLog || 'Ham log bulunamadı.')}
+ ${esc(b.pr.body)}
+ ` : '${esc(b.suggestedCmd)}
+