From d9de3d160236f63743f168b56046d47efad47062 Mon Sep 17 00:00:00 2001 From: Ziya Yesilbahce Date: Tue, 17 Nov 2026 13:12:00 +0300 Subject: [PATCH] =?UTF-8?q?feat(engine):=206=20dosya=20(collector.go,=20si?= =?UTF-8?q?mulation.go...)=20g=C3=BCncellemeleri=20ve=20iyile=C5=9Ftirmele?= =?UTF-8?q?r?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REFACTOR_INDEX.md | 69 ++ internal/gitengine/collector.go | 314 -------- internal/gitengine/collector_github.go | 334 ++++++++ internal/gitengine/simulation.go | 520 ------------ .../gitengine/simulation_enterprise_mock.go | 523 ++++++++++++ web/modules/api.js | 25 + web/modules/canvas.js | 756 ++++++++++++++++++ web/modules/constants.js | 16 + web/modules/dock.js | 261 ++++++ web/modules/inspector.js | 708 ++++++++++++++++ web/modules/state.js | 144 ++++ web/modules/utils.js | 215 +++++ 12 files changed, 3051 insertions(+), 834 deletions(-) create mode 100644 REFACTOR_INDEX.md create mode 100644 internal/gitengine/collector_github.go create mode 100644 internal/gitengine/simulation_enterprise_mock.go create mode 100644 web/modules/api.js create mode 100644 web/modules/canvas.js create mode 100644 web/modules/constants.js create mode 100644 web/modules/dock.js create mode 100644 web/modules/inspector.js create mode 100644 web/modules/state.js create mode 100644 web/modules/utils.js 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 = ` +
+ ${isWorkingTreeWip ? '✏️ Çalışma Alanı' : esc(truncate(b.name, 22))} + ${badgeText} +
+
${esc(truncate(subText, 32))}
+ ${alertsHtml ? `
${alertsHtml}
` : ''} +
${actionRowHtml}
+ `; + + card.querySelectorAll('button[data-act]').forEach((btn) => { + btn.addEventListener('pointerdown', (ev) => ev.stopPropagation()); + btn.addEventListener('click', (ev) => { + ev.stopPropagation(); + const act = btn.getAttribute('data-act'); + if (act === 'inspect' && onSelectBranch) onSelectBranch(b.id); + else if (act === 'checkout' && onCheckoutBranch) onCheckoutBranch(b.id, btn); + else if (act === 'checkout-main' && onCheckoutBranch) onCheckoutBranch('main', btn); + else if (act === 'merge' && onMergeBranch) onMergeBranch(b.id, btn); + else if (act === 'promote' && onPromoteBranch) onPromoteBranch(b.id, undefined, undefined, btn); + else if (act === 'resolve' && onOpenConflictStudio) onOpenConflictStudio(b.id); + else if (act === 'delete' && onDeleteBranch) onDeleteBranch(b.id, btn); + }); + }); + + card.addEventListener('pointerdown', (ev) => { + if (ev.target.closest('button')) return; + state.drag = { + branchId: b.id, + startX: ev.clientX, + startY: ev.clientY, + currentX: ev.clientX, + currentY: ev.clientY, + hasMoved: false, + }; + try { + card.setPointerCapture?.(ev.pointerId); + } catch {} + }); + + card.addEventListener('click', (ev) => { + if (state.drag?.hasMoved) return; + ev.stopPropagation(); + if (onSelectBranch) onSelectBranch(b.id); + }); + + fo.appendChild(card); + return fo; +} + +export function renderSVG(callbacks = {}) { + const snap = state.snapshot; + if (!snap || !el.svg) return; + + const { onSelectBranch, onSelectNode, onCheckoutBranch, onMergeBranch, onPromoteBranch, onDeleteBranch, onOpenConflictStudio } = callbacks; + + const nodes = snap.nodes || []; + const branches = snap.branches || []; + const visibleBranches = branches.filter((b) => state.showMergedArches || b.state !== 'merged'); + const apexLayout = layoutOpenApexPositions(visibleBranches); + state.apexLayout = apexLayout; + + const maxSpineIdx = Math.max(nodes.length - 1, ...visibleBranches.map((b) => b.endSpineIndex || 0), 6); + const maxMergedUpperLane = Math.max(1, ...visibleBranches.filter((b) => b.hemisphere === 'upper' && b.state === 'merged').map((b) => b.lane || 1)); + const maxApexX = Math.max(0, ...Array.from(apexLayout.values()).map((v) => v.apexX)); + + const minY = Math.min(0, MAIN_Y - LANE_BASE_OFFSET - (maxMergedUpperLane - 1) * LANE_STEP_Y - 130); + const maxY = Math.max(680, MAIN_Y + LANE_BASE_OFFSET + 220); + const sceneW = Math.max(1280, SPINE_START_X + (maxSpineIdx + 2) * SPINE_STEP_X + 140, maxApexX + 200); + const sceneH = maxY - minY; + + const viewW = sceneW / state.zoom; + const viewH = sceneH / state.zoom; + el.svg.setAttribute('viewBox', `${state.panX} ${minY + state.panY} ${viewW} ${viewH}`); + if (el.zoomReset) el.zoomReset.textContent = `${Math.round(state.zoom * 100)}%`; + + el.svg.innerHTML = ''; + + // 1. SVG + const defs = svgEl('defs'); + defs.innerHTML = ` + + + + + + + + + + + + + + + `; + el.svg.appendChild(defs); + + // 2. Background horizontal dashed guide rails + el.svg.appendChild(svgEl('line', { x1: 40, y1: MAIN_Y - LANE_BASE_OFFSET, x2: sceneW - 40, y2: MAIN_Y - LANE_BASE_OFFSET, class: 'svg-guide-line' })); + el.svg.appendChild(svgEl('line', { x1: 40, y1: MAIN_Y + LANE_BASE_OFFSET, x2: sceneW - 40, y2: MAIN_Y + LANE_BASE_OFFSET, class: 'svg-guide-line' })); + + // 3. Parabolic Curves Layer + const arcLayer = svgEl('g', { id: 'arc-layer' }); + const capsuleLayer = svgEl('g', { id: 'capsule-layer' }); + + const ordered = [...visibleBranches].sort((a, b) => (a.state === 'merged' ? 0 : 1) - (b.state === 'merged' ? 0 : 1)); + ordered.forEach((b) => { + const geom = computeBranchGeometry(b, null, null, apexLayout); + const visible = matchesFilter(b); + const isSelected = state.selectedBranchId === b.id; + const tone = branchToneClass(b); + const strokeColor = branchStrokeColor(b); + + if (b.state === 'merged' && geom.areaD) { + arcLayer.appendChild(svgEl('path', { + d: geom.areaD, + fill: strokeColor, + class: `svg-arc-area ${isSelected ? 'selected' : ''} ${visible ? '' : 'dimmed'}`, + })); + } + + const openCls = ['svg-arc-path', tone]; + if (isSelected) openCls.push('selected'); + if (!visible) openCls.push('dimmed'); + const openAttrs = { d: geom.openD, class: openCls.join(' ') }; + if (b.pr?.ci?.state === 'FAILURE') openAttrs.filter = 'url(#glow-red)'; + const openPath = svgEl('path', openAttrs); + openPath.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onSelectBranch) onSelectBranch(b.id); + }); + arcLayer.appendChild(openPath); + + if (b.state === 'merged' && geom.closeD) { + const closePath = svgEl('path', { d: geom.closeD, class: openCls.join(' ') }); + closePath.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onSelectBranch) onSelectBranch(b.id); + }); + arcLayer.appendChild(closePath); + + if (b.hasLocal || b.originGone) { + const mergeX = geom.endX || xOfSpine(b.endSpineIndex || b.startSpineIndex || 0); + const remY = MAIN_Y + 56 + (((b.endSpineIndex || 0) % 2) * 30); + const remX = mergeX + 18; + const remPath = svgEl('path', { + d: `M ${mergeX} ${MAIN_Y} C ${mergeX} ${MAIN_Y + 30}, ${remX - 16} ${remY}, ${remX} ${remY}`, + class: `svg-local-remnant-path ${isSelected ? 'selected' : ''} ${visible ? '' : 'dimmed'}`, + }); + remPath.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onSelectBranch) onSelectBranch(b.id); + }); + arcLayer.appendChild(remPath); + + const remFo = svgEl('foreignObject', { + x: remX, + y: remY - 12, + width: 150, + height: 26, + class: `fo-capsule ${visible ? '' : 'dimmed'}`, + 'data-remnant-branch-id': b.id, + }); + const remPill = document.createElementNS(XHTML_NS, 'div'); + remPill.className = `cap-local-remnant ${isSelected ? 'selected' : ''}`; + remPill.innerHTML = ` + 💻 ${b.isHead ? 'HEAD·' : ''}${esc(truncate(b.name, 13))} + + `; + remPill.querySelector('button[data-act="delete"]')?.addEventListener('pointerdown', (ev) => ev.stopPropagation()); + remPill.querySelector('button[data-act="delete"]')?.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onDeleteBranch) onDeleteBranch(b.id); + }); + remPill.addEventListener('pointerdown', (ev) => ev.stopPropagation()); + remPill.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (onSelectBranch) onSelectBranch(b.id); + }); + remFo.appendChild(remPill); + capsuleLayer.appendChild(remFo); + } + } else { + arcLayer.appendChild(svgEl('line', { + x1: geom.apexX, + y1: geom.apexY, + x2: geom.apexX + 95, + y2: geom.apexY, + class: `svg-open-tail ${tone} ${visible ? '' : 'dimmed'}`, + })); + } + + const dot = svgEl('circle', { + cx: geom.apexX, + cy: geom.apexY, + r: isSelected ? 6 : 4.5, + class: `svg-apex-dot ${tone}`, + }); + arcLayer.appendChild(dot); + + const fo = buildCapsuleForeignObject(b, geom, isSelected, visible, tone, callbacks); + capsuleLayer.appendChild(fo); + }); + + el.svg.appendChild(arcLayer); + + // 4. Central Spine Rail Line + const spineLineX1 = 40; + const spineLineX2 = sceneW - 60; + el.svg.appendChild(svgEl('line', { + x1: spineLineX1, + y1: MAIN_Y, + x2: spineLineX2, + y2: MAIN_Y, + stroke: 'url(#main-rail-grad)', + filter: 'url(#glow-green)', + class: 'svg-spine-line', + })); + + const defBranch = snap.repo?.defaultBranch || 'main'; + const mainTagW = Math.max(58, defBranch.length * 8 + 22); + el.svg.appendChild(svgEl('rect', { x: 22, y: MAIN_Y - 13, width: mainTagW, height: 26, rx: 8, class: 'svg-main-tag-bg' })); + el.svg.appendChild(svgEl('text', { x: 22 + mainTagW / 2, y: MAIN_Y + 4, class: 'svg-main-tag-txt' }, defBranch)); + + // 5. Commit Nodes on the Central Spine + const nodeLayer = svgEl('g', { id: 'node-layer' }); + nodes.forEach((n, idx) => { + const cx = xOfSpine(n.spineIndex); + const isLatest = idx === nodes.length - 1; + const cls = ['svg-node-circle']; + if (n.isMerge) cls.push('merge-node'); + if (n.isHead || isLatest) cls.push('head-node'); + + const circle = svgEl('circle', { + cx, + cy: MAIN_Y, + r: isLatest ? 8.5 : (n.isMerge ? 7 : 5.5), + class: cls.join(' '), + }); + circle.addEventListener('click', (ev) => { + ev.stopPropagation(); + state.selectedNodeSha = n.shortSha; + state.selectedBranchId = null; + if (onSelectNode) onSelectNode(n.shortSha); + }); + nodeLayer.appendChild(circle); + + nodeLayer.appendChild(svgEl('text', { + x: cx, + y: MAIN_Y - 14, + class: `svg-node-sha ${isLatest ? 'latest' : ''}`, + }, n.shortSha)); + + nodeLayer.appendChild(svgEl('text', { + x: cx, + y: MAIN_Y + 23, + class: 'svg-node-label', + }, truncate(n.subject, 19))); + + if (n.tag) { + const tw = n.tag.length * 6.8 + 14; + nodeLayer.appendChild(svgEl('rect', { x: cx - tw / 2, y: MAIN_Y - 40, width: tw, height: 17, rx: 5, class: 'svg-node-tag-bg' })); + nodeLayer.appendChild(svgEl('text', { x: cx, y: MAIN_Y - 28, class: 'svg-node-tag-txt' }, n.tag)); + } + }); + + el.svg.appendChild(nodeLayer); + el.svg.appendChild(capsuleLayer); + el.svg.appendChild(svgEl('path', { id: 'drag-preview-path', class: 'svg-drag-preview', d: '' })); +} + +export function setupCanvasInteractions(onRenderSVG = null) { + if (!el.svg) return; + + el.svg.addEventListener('pointerdown', (ev) => { + if (ev.target.closest('.fo-capsule') || ev.target.closest('circle') || ev.target.closest('path')) return; + state.panning = { + startX: ev.clientX, + startY: ev.clientY, + initialPanX: state.panX, + initialPanY: state.panY, + }; + try { + el.svg.setPointerCapture?.(ev.pointerId); + } catch {} + }); + + window.addEventListener('pointermove', (ev) => { + if (state.panning) { + const dx = (ev.clientX - state.panning.startX) / state.zoom; + const dy = (ev.clientY - state.panning.startY) / state.zoom; + state.panX = state.panning.initialPanX - dx; + state.panY = state.panning.initialPanY - dy; + if (onRenderSVG) onRenderSVG(); + return; + } + + if (state.drag) { + const dx = ev.clientX - state.drag.startX; + const dy = ev.clientY - state.drag.startY; + if (Math.abs(dx) > 4 || Math.abs(dy) > 4) { + state.drag.hasMoved = true; + } + } + }); + + window.addEventListener('pointerup', () => { + state.panning = null; + state.drag = null; + }); + + el.svg.addEventListener('wheel', (ev) => { + ev.preventDefault(); + const factor = ev.deltaY < 0 ? 1.08 : 0.92; + state.zoom = Math.min(2.5, Math.max(0.4, state.zoom * factor)); + if (onRenderSVG) onRenderSVG(); + }, { passive: false }); + + if (el.zoomReset) { + el.zoomReset.addEventListener('click', () => { + state.zoom = 1; + state.panX = 0; + state.panY = 0; + if (onRenderSVG) onRenderSVG(); + }); + } + + const btnZoomIn = document.getElementById('zoom-in'); + if (btnZoomIn) { + btnZoomIn.addEventListener('click', () => { + state.zoom = Math.min(2.5, state.zoom * 1.15); + if (onRenderSVG) onRenderSVG(); + }); + } + + const btnZoomOut = document.getElementById('zoom-out'); + if (btnZoomOut) { + btnZoomOut.addEventListener('click', () => { + state.zoom = Math.max(0.4, state.zoom * 0.85); + if (onRenderSVG) onRenderSVG(); + }); + } + + if (el.toggleMerged) { + el.toggleMerged.addEventListener('change', (ev) => { + state.showMergedArches = ev.target.checked; + if (onRenderSVG) onRenderSVG(); + }); + } +} + diff --git a/web/modules/constants.js b/web/modules/constants.js new file mode 100644 index 0000000..32c23f0 --- /dev/null +++ b/web/modules/constants.js @@ -0,0 +1,16 @@ +// web/modules/constants.js - GitArc layout, geometry and system constants + +export const SVG_NS = 'http://www.w3.org/2000/svg'; +export const XHTML_NS = 'http://www.w3.org/1999/xhtml'; + +export const MAIN_Y = 300; +export const SPINE_START_X = 140; +export const SPINE_STEP_X = 156; +export const LANE_BASE_OFFSET = 100; +export const LANE_STEP_Y = 98; +export const FO_W = 222; +export const FO_H = 114; +export const MERGED_FO_W = 188; +export const MERGED_FO_H = 34; +export const OPEN_CAPSULE_MIN_GAP_X = 238; +export const REPO_STORAGE_KEY = 'gitarc_repo_id'; diff --git a/web/modules/dock.js b/web/modules/dock.js new file mode 100644 index 0000000..1980838 --- /dev/null +++ b/web/modules/dock.js @@ -0,0 +1,261 @@ +// web/modules/dock.js - Bottom Dock, Hata Radarı and live logging panel +import { state, el } from './state.js'; +import { esc, truncate, showToast } from './utils.js'; +import { apiCall } from './api.js'; + +export function getMergedLogs() { + const serverLogs = state.snapshot?.logs || []; + const seenMsgs = new Set(serverLogs.map((l) => `${l.level}:${l.message}`)); + const extra = state.clientLogs.filter((l) => !seenMsgs.has(`${l.level}:${l.message}`)); + return [...extra, ...serverLogs].slice(0, 60); +} + +export function renderLogBadge(onRenderModal = null) { + const logs = getMergedLogs(); + const errCount = logs.filter((l) => l.level === 'error').length; + if (el.logCount) { + el.logCount.textContent = String(errCount > 0 ? errCount : logs.length); + } + if (el.btnLogsModal) { + el.btnLogsModal.classList.toggle('danger', errCount > 0); + } + if (el.logsModal && !el.logsModal.hidden && onRenderModal) { + onRenderModal(); + } +} + +export function recordClientLog(level, action, message, detail = '', onRenderModal = null) { + const now = new Date(); + const ts = now.toTimeString().slice(0, 8); + state.clientLogs.unshift({ + id: `cli-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`, + timestamp: ts, + level, + action, + message: String(message || ''), + detail: String(detail || ''), + }); + if (state.clientLogs.length > 40) { + state.clientLogs.length = 40; + } + renderLogBadge(onRenderModal); +} + +export function renderDockStreams() { + const logs = getMergedLogs(); + const actionLogs = state.snapshot?.actionLogs || []; + + if (el.dockLogCount) el.dockLogCount.textContent = logs.length; + if (el.dockActionCount) el.dockActionCount.textContent = actionLogs.length; + + if (el.dockLogsStream) { + el.dockLogsStream.innerHTML = ''; + if (logs.length === 0) { + el.dockLogsStream.innerHTML = '
Henüz sistem veya Git logu yok.
'; + } else { + logs.slice(0, 50).forEach((l) => { + const item = document.createElement('div'); + item.className = `dock-log-item ${l.level || 'info'}`; + item.innerHTML = ` + ${esc(l.timestamp || '')} + ${esc(l.action || '')} + ${esc(l.message || '')} + ${l.detail ? `${esc(truncate(l.detail, 60))}` : ''} + `; + el.dockLogsStream.appendChild(item); + }); + } + } + + if (el.dockActionsStream) { + el.dockActionsStream.innerHTML = ''; + if (actionLogs.length === 0) { + el.dockActionsStream.innerHTML = '
Henüz kaydedilmiş işlem yok.
'; + } else { + actionLogs.slice(0, 50).forEach((a) => { + const item = document.createElement('div'); + item.className = `dock-log-item ${a.level === 'error' ? 'danger' : (a.level === 'warn' ? 'warn' : 'ok')}`; + item.innerHTML = ` + ${esc(a.timestamp || '')} + ${esc(a.action || '')} + ${esc(a.branch ? a.branch + ' · ' : '')}${esc(a.message || '')} + ${a.detail ? `${esc(truncate(a.detail, 60))}` : ''} + `; + el.dockActionsStream.appendChild(item); + }); + } + } +} + +export function renderRadar(callbacks = {}) { + const { onSelectBranch, onOpenConflictStudio, onPruneGone } = callbacks; + const diags = state.snapshot?.diagnostics || []; + if (el.dockRadarCount) el.dockRadarCount.textContent = diags.length; + if (el.radarCount) el.radarCount.textContent = `${diags.length} uyarı`; + if (!el.radarList) return; + el.radarList.innerHTML = ''; + + if (diags.length === 0) { + const clean = document.createElement('div'); + clean.className = 'empty-detail'; + clean.textContent = 'Radar temiz — çakışma, Cross-PR veya CI hatası yok.'; + el.radarList.appendChild(clean); + renderDockStreams(); + return; + } + + const branches = state.snapshot?.branches || []; + + diags.forEach((d) => { + const b = branches.find((x) => x.id === d.branchId || x.name === d.branchName); + const card = document.createElement('div'); + const sev = d.severity || 'warning'; + card.className = `radar-card ${sev}`; + + let badgeClass = 'warn'; + let badgeLabel = '⚠️ UYARI'; + if (sev === 'critical') { + badgeClass = 'danger'; + badgeLabel = '🚨 KRİTİK'; + } else if (sev === 'info') { + badgeClass = 'sky'; + badgeLabel = 'ℹ️ BİLGİ'; + } + + let kindLabel = ''; + if (d.kind === 'ci_failure') kindLabel = 'CI Test Hatası'; + else if (d.kind === 'conflict') kindLabel = 'Merge Çakışması'; + else if (d.kind === 'cross_pr') kindLabel = 'Cross-PR Çarpışması'; + else if (d.kind === 'prune_candidate') kindLabel = 'Silinmiş/Kalıntı Dal'; + + const files = d.files || b?.conflict?.files || []; + let filesHtml = ''; + if (files.length > 0) { + filesHtml = files.map((f) => `${esc(f)}`).join(''); + } + + let ciSnippet = ''; + if (b?.pr?.ci?.failureSummary) { + ciSnippet = b.pr.ci.failureSummary; + } else if (b?.pr?.ci?.rawLog && (b?.pr?.ci?.state === 'FAILURE' || b?.pr?.ci?.status === 'failure')) { + ciSnippet = b.pr.ci.rawLog.split('\n').filter(Boolean).slice(0, 3).join('\n'); + } + + let actBtnText = '🎯 Odaklan & İncele'; + let actAction = 'select'; + if (d.kind === 'conflict') { + actBtnText = '⚡ Çakışma Stüdyosu'; + actAction = 'studio'; + } else if (d.kind === 'ci_failure') { + actBtnText = '🔍 CI Hatasını Gör'; + actAction = 'select'; + } else if (d.kind === 'prune_candidate') { + actBtnText = '🧹 Dalı Temizle'; + actAction = 'prune'; + } + + const suggestedCmd = b?.suggestedCmd || d.actionHint || ''; + + card.innerHTML = ` +
+
+ ${badgeLabel}${kindLabel ? ' · ' + kindLabel : ''} + ${esc(d.branchName || 'Genel')} + ${esc(d.title)} +
+
+ +
+
+
+
${esc(d.detail)}
+ ${filesHtml ? `
Etkilenen Dosyalar: ${filesHtml}
` : ''} + ${ciSnippet ? `
${esc(ciSnippet)}
` : ''} + ${suggestedCmd ? ` +
+ ${esc(suggestedCmd)} + +
+ ` : ''} +
+ `; + + card.querySelector('button[data-act]')?.addEventListener('click', (ev) => { + ev.stopPropagation(); + const act = ev.currentTarget.dataset.act; + const brId = ev.currentTarget.dataset.branch; + if (act === 'studio' && brId && onOpenConflictStudio) { + onOpenConflictStudio(brId); + } else if (act === 'prune' && onPruneGone) { + onPruneGone(); + } else if (brId && onSelectBranch) { + onSelectBranch(brId); + } + }); + + card.querySelector('.copy-cmd-btn')?.addEventListener('click', async (ev) => { + ev.stopPropagation(); + const cmd = ev.currentTarget.dataset.cmd; + if (!cmd) return; + try { + await navigator.clipboard.writeText(cmd); + showToast('Komut panoya kopyalandı', 'ok'); + } catch { + showToast('Pano izni verilemedi', 'warn'); + } + }); + + card.addEventListener('click', () => { + if (d.branchId && onSelectBranch) onSelectBranch(d.branchId); + }); + + el.radarList.appendChild(card); + }); + + renderDockStreams(); +} + +export function setupBottomDock(onApplySnapshot = null) { + const tabs = [ + { tab: el.dockTabRadar, pane: el.dockPaneRadar }, + { tab: el.dockTabLogs, pane: el.dockPaneLogs }, + { tab: el.dockTabActions, pane: el.dockPaneActions }, + ]; + + tabs.forEach(({ tab, pane }) => { + tab?.addEventListener('click', () => { + tabs.forEach((t) => { + t.tab?.classList.remove('active'); + t.tab?.setAttribute('aria-selected', 'false'); + t.pane?.classList.add('hidden'); + t.pane?.classList.remove('active'); + }); + tab.classList.add('active'); + tab.setAttribute('aria-selected', 'true'); + pane?.classList.remove('hidden'); + pane?.classList.add('active'); + }); + }); + + el.dockToggleBtn?.addEventListener('click', () => { + const isCollapsed = el.dock?.classList.toggle('dock-collapsed'); + if (el.dockToggleBtn) { + el.dockToggleBtn.textContent = isCollapsed ? '▲' : '▼'; + } + }); + + el.dockClearBtn?.addEventListener('click', async () => { + state.clientLogs = []; + if (!state.offlineMode) { + try { + const snap = await apiCall('/api/logs/clear', 'POST', {}); + if (onApplySnapshot) onApplySnapshot(snap); + } catch (err) { + showToast(err.message, 'danger'); + } + } + renderLogBadge(); + renderDockStreams(); + showToast('Loglar temizlendi', 'info'); + }); +} diff --git a/web/modules/inspector.js b/web/modules/inspector.js new file mode 100644 index 0000000..7274c75 --- /dev/null +++ b/web/modules/inspector.js @@ -0,0 +1,708 @@ +// web/modules/inspector.js - Right detail inspector panel and form controller +import { state, el } from './state.js'; +import { + esc, truncate, isMergedOrGone, isSecretFile, suggestUniqueBranchName, showToast +} from './utils.js'; +import { apiCall } from './api.js'; + +export function wireProposalActions(onApplySnapshot = null) { + const prop = state.snapshot?.pendingProposal; + if (!prop) return; + + const bIn = document.getElementById('prop-edit-branch'); + const mIn = document.getElementById('prop-edit-message'); + const tIn = document.getElementById('prop-edit-title'); + const dIn = document.getElementById('prop-edit-body'); + + const saveDraft = () => { + state.proposalDraftEdits = { + id: prop.id, + branch: bIn ? bIn.value.trim() : prop.branchName, + message: mIn ? mIn.value : prop.message, + title: tIn ? tIn.value.trim() : prop.prTitle, + body: dIn ? dIn.value : prop.prBody, + }; + }; + + bIn?.addEventListener('input', saveDraft); + mIn?.addEventListener('input', saveDraft); + tIn?.addEventListener('input', saveDraft); + dIn?.addEventListener('input', saveDraft); + + document.getElementById('act-proposal-approve')?.addEventListener('click', async () => { + const branchName = bIn ? bIn.value.trim() : prop.branchName; + const message = mIn ? mIn.value.trim() : prop.message; + const prTitle = tIn ? tIn.value.trim() : prop.prTitle; + const prBody = dIn ? dIn.value : prop.prBody; + + if (!branchName) { + showToast('Lütfen geçerli bir dal adı girin', 'danger'); + return; + } + if (!message) { + showToast('Commit mesajı boş olamaz', 'danger'); + return; + } + + const payload = { + proposalId: prop.id, + branchName, + message, + prTitle, + prBody, + }; + + if (!state.offlineMode) { + try { + const snap = await apiCall('/api/proposal/approve', 'POST', payload); + delete state.proposalDraftEdits; + showToast(`✓ AI önerisi onaylandı: ${branchName} dalı oluşturuldu ve PR açıldı!`, 'ok'); + if (onApplySnapshot) onApplySnapshot(snap); + } catch (err) { + showToast(`Hata: ${err.message}`, 'danger'); + } + } else if (window.LocalFallbackEngine) { + try { + const snap = window.LocalFallbackEngine.approveProposal(payload); + delete state.proposalDraftEdits; + showToast(`✓ AI önerisi onaylandı (Offline Mod): ${branchName}`, 'ok'); + if (onApplySnapshot) onApplySnapshot(snap); + } catch (err) { + showToast(`Hata: ${err.message}`, 'danger'); + } + } + }); + + document.getElementById('act-proposal-dismiss')?.addEventListener('click', async () => { + delete state.proposalDraftEdits; + showToast('AI commit/PR önerisi reddedildi (dosyalarınız korundu)', 'info'); + if (!state.offlineMode) { + try { + const dismissedSnap = await apiCall('/api/proposal/dismiss', 'POST', {}); + if (onApplySnapshot) onApplySnapshot(dismissedSnap); + } catch (_) {} + } else if (window.LocalFallbackEngine) { + window.LocalFallbackEngine.dismissProposal(); + if (onApplySnapshot) onApplySnapshot(state.snapshot); + } + }); +} + +export function renderInspector(callbacks = {}) { + const snap = state.snapshot; + if (!snap || !el.detail) return; + + const { + onCheckoutBranch, onMergeBranch, onPromoteBranch, onDeleteBranch, + onOpenConflictStudio, onFixCI, onLocalTestRun, onEditPR, onAmendCommit, + onCommitWorkingTree, onDiscardWorkingTree, onApplySnapshot + } = callbacks; + + if (state.selectedNodeSha) { + const node = snap.nodes.find((n) => n.shortSha === state.selectedNodeSha); + if (node) { + el.detail.innerHTML = ` +
+
+

Commit ${esc(node.shortSha)}

+ ${node.tag ? `${esc(node.tag)}` : ''} +
+
+ ${esc(node.author)} + ${esc(node.relativeTime)} + ${node.isMerge ? 'Merge Node' : ''} +
+
+
+

Commit Mesajı

+
${esc(node.subject)}
+
+
🔒 main omurgasındaki commit mesajları tarihçe güvenliği için kilitlidir.
+ `; + return; + } + } + + let proposalHtml = ''; + if (snap.pendingProposal) { + const prop = snap.pendingProposal; + const edits = (state.proposalDraftEdits && state.proposalDraftEdits.id === prop.id) + ? state.proposalDraftEdits + : null; + const branchVal = edits ? edits.branch : prop.branchName; + const msgVal = edits ? edits.message : prop.message; + const titleVal = edits ? edits.title : (prop.prTitle || ''); + const bodyVal = edits ? edits.body : (prop.prBody || ''); + + proposalHtml = ` +
+
+

+ 🤖 Claude / AI Commit & PR Önerisi + Kullanıcı Onayı Bekliyor +

+ ${esc(prop.createdAt || '')} +
+
+ Claude bir commit ve PR önerisi hazırladı. Bu öneri ${esc(prop.baseBranch || 'origin/main')} tabanlı yeni bir dal açacak, yalnız aşağıdaki açık dosyaları stage edecek ve PR oluşturacaktır. İnceleyip onaylayabilir veya başlık/açıklama alanlarını doğrudan düzenleyebilirsiniz. +
+ +
+ + +
+ +
+ +
+ ${(prop.files || []).map((f) => `${esc(f)}`).join('')} +
+
+ + ${prop.diffStat ? ` +
+ +
${esc(prop.diffStat)}
+
+ ` : ''} + +
+ +
${esc(prop.shieldResult || '✓ 0 secret, 0 özel anahtar, 0 .gitignore ihlali (Tüm dosyalar güvenli)')}
+
+ +
+ +
+ ${esc(prop.countCheckMessage || `✓ ${prop.files?.length || 0} dosya seçildi`)} +
+
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+ `; + } + + const b = snap.branches.find((x) => x.id === state.selectedBranchId); + if (!b) { + el.detail.innerHTML = ` + ${proposalHtml} +
+

İ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.

+
+ `; + if (snap.pendingProposal) { + wireProposalActions(onApplySnapshot); + } + return; + } + + const isOpen = b.state === 'open'; + const isVirtualWip = b.id === 'local-wip-working-tree'; + const hasConflict = Boolean(b.conflict?.hasConflict && !b.conflict.resolved); + const isRemoteOnly = !b.hasLocal && b.hasRemote && isOpen; + const isLive = snap.repo.mode === 'live'; + const ciState = b.pr?.ci?.state || ''; + const isRunning = ciState === 'RUNNING'; + const isQueued = Boolean(state.pendingAutoMerge[b.id]); + const canCommitWorkingTree = isVirtualWip || (b.uncommittedCount || 0) > 0 || (b.isHead && (state.snapshot?.repo?.dirtyCount || 0) > 0); + const isAlreadySynced = b.aheadMain === 0 && (b.uncommittedCount || 0) === 0 && !isVirtualWip; + const canPromote = isOpen && b.hemisphere === 'lower' && !isVirtualWip && !canCommitWorkingTree && !isAlreadySynced; + const hasOpenPR = Boolean(b.pr && b.pr.number > 0 && b.pr.reviewState !== 'MERGED'); + const canMerge = isOpen && hasOpenPR && !hasConflict && !isVirtualWip && ciState !== 'FAILURE'; + + let html = ` + ${proposalHtml} +
+
+

${isVirtualWip ? '✏️ Çalışma Alanı (Kaydedilmemiş Değişiklikler)' : esc(b.name)}

+ + ${isVirtualWip ? 'Yerel Taslak · Uncommitted' : (b.state === 'merged' ? 'Tam Parabol' : (isAlreadySynced ? '✓ main ile Eşit (Kalıntı Dal)' : (b.hemisphere === 'lower' && b.aheadMain === 0 ? '🌱 Yeni Yerel Dal' : b.hemisphere === 'lower' ? 'Alt Ray · Local' : 'Üst Ray · PR')))} + +
+
+ ${b.isHead ? 'HEAD (Aktif Dal)' : ''} + ${b.author ? `${esc(b.author)}` : ''} + ${b.pr?.ci ? `CI: ${esc(b.pr.ci.state)}` : ''} + ${b.originGone ? 'origin: gone' : ''} +
+
+ ${!b.isHead && isOpen && !isVirtualWip ? `` : ''} + ${b.isHead && isAlreadySynced && !isVirtualWip ? `` : ''} + ${canPromote && !hasOpenPR ? `` : ''} + ${hasOpenPR && !isVirtualWip ? ` +
+ + ${isRunning + ? `` + : ``} +
+ ` : ''} + ${hasConflict ? `` : ''} + ${!isVirtualWip && (b.state !== 'merged' || b.hasLocal || b.originGone || b.hasRemote) ? `` : ''} +
+
+ `; + + const upperSummary = b.pr + ? `PR #${b.pr.number} · ${b.pr.reviewState}` + : (isRemoteOnly ? `origin/${truncate(b.name, 16)}` : (b.originGone ? 'origin: gone' : 'PR Yok')); + + const lowerSummary = isVirtualWip + ? `${b.uncommittedCount || snap.repo?.dirtyCount || 0} dosya bekliyor` + : (!b.hasLocal ? 'Yerelde Yok' : (b.isHead ? 'HEAD (Aktif)' : `↑${b.aheadMain || 0} / ↓${b.behindMain || 0}`)); + + html += ` +
+
+ + ☁️ Üst Ray · Remote / PR + ${esc(upperSummary)} + +
+ ${b.pr ? ` +
PR #${b.pr.number} · ${esc(b.pr.reviewState)}
+
${esc(truncate(b.pr.title, 56))}
+
CI: ${esc(b.pr.ci?.workflow || 'ci.yml')} (${esc(b.pr.ci?.duration || '—')})
+ ` : ` +
${isRemoteOnly ? `Remote aktif: origin/${esc(b.name)}` : (b.originGone ? 'Remote silindi (origin: gone)' : 'Henüz PR / Remote yok')}
+
${isRemoteOnly ? 'Yerelde kopyası silinmiş uzak dal' : 'Alt rayda yerel çalışma'}
+ `} +
+
+ +
+ + 💻 Alt Ray · Local + ${esc(lowerSummary)} + +
+ ${isVirtualWip ? ` +
Konum: main omurgası (Kaydedilmemiş Çalışma)
+
Durum: Henüz bir dala veya commite aktarılmamış
+
Değişen Dosyalar: ${b.uncommittedCount || state.snapshot?.repo?.dirtyCount || 0} adet dosya
+ ` : (!b.hasLocal ? ` +
${b.state === 'merged' && !b.originGone ? '✓ Yerel kalıntı dal temizlendi' : `Yerelde dal yok (origin/${esc(b.name)})`}
+
SHA: ${esc(b.localSha || b.mergeSha || b.baseSha)}
+
main farkı: ↑${b.aheadMain || 0} / ↓${b.behindMain || 0}
+ ` : ` + ${b.state === 'merged' ? '
⚠ Birleşmiş yerel kalıntı (tek tıkla temizlenebilir)
' : (b.aheadMain === 0 && !isVirtualWip ? '
🌱 main omurgasında taze dal (ilk commitinizi bekliyor)
' : '')} +
SHA: ${esc(b.localSha || b.mergeSha || b.baseSha)}
+
main farkı: ↑${b.aheadMain || 0} / ↓${b.behindMain || 0}
+
Uncommitted (Staged + Untracked): ${b.uncommittedCount || (b.isHead ? state.snapshot?.repo?.dirtyCount : 0) || 0} dosya
+ `)} +
+
+
+ `; + + if (b.conflict) { + const resolved = b.conflict.resolved; + html += ` +
+

+ ${resolved ? '✓ Çakışma Çözüldü' : (b.conflict.isChangelogOrLock ? '⚠ CHANGELOG / Lockfile Çakışması' : '⚠ Merge Çakışması')} + ${esc(b.conflict.strategy || 'merge-tree')} +

+
${resolved ? esc(b.conflict.resolvedNote) : `git merge-tree --write-tree: ${esc((b.conflict.files || []).join(', '))}`}
+
${esc(b.conflict.previewUnified || '')}
+ ${!resolved ? `
` : ''} +
+ `; + } + + if (b.crossPr?.length) { + html += ` +
+

⇄ Cross-PR Dosya Çarpışması

+ ${b.crossPr.map((c) => ` +
${c.otherPrNumber ? 'PR #' + c.otherPrNumber : ''} (${esc(c.otherBranch)}): ${esc(c.sharedFiles.join(', '))}
+ `).join('')} +
+ `; + } + + if (b.pr?.ci?.state === 'FAILURE') { + const extracts = b.pr.ci.extracts || []; + const localRunOut = state.localRunOutput[b.id] || ''; + html += ` +
+

+ Gürültüsüz CI Hata Ayıklayıcı + ${extracts.length} kritik bulgu +

+
+ ${extracts.map((ex) => ` +
+
+ ${esc(ex.kind.toUpperCase())} · ${esc(ex.symbol)} + ${esc(ex.fileLine || '')} +
+
${esc(ex.message)}
+ ${ex.reproCmd ? `
$ ${esc(ex.reproCmd)}
` : ''} +
+ `).join('')} +
+
+ ${!isLive ? '' : ''} + + +
+
${esc(localRunOut || b.pr.ci.rawLog || 'Ham log bulunamadı.')}
+
+ `; + } + + if (canCommitWorkingTree) { + const isMerged = isMergedOrGone(b) || b.state === 'merged' || b.pr?.reviewState === 'MERGED'; + const candidateFiles = (b.changedFiles || []).filter(Boolean); + const secretFile = candidateFiles.find((f) => isSecretFile(f, snap)); + + let defaultWtBranch = b.name; + let branchPlaceholder = 'feat/ozellik-adi'; + let defaultCommitMsg = b.lastCommitMsg || ''; + if (/update\s+\d+\s+files/i.test(defaultCommitMsg) || defaultCommitMsg.startsWith('Pushlanmamış yerel çalışma')) { + defaultCommitMsg = ''; + } + let defaultPrTitle = b.draftPrTitle || defaultCommitMsg; + if (/update\s+\d+\s+files/i.test(defaultPrTitle)) { + defaultPrTitle = ''; + } + let defaultPrBody = b.draftPrBody || ''; + + if (isVirtualWip || isMerged) { + defaultWtBranch = suggestUniqueBranchName('feat', candidateFiles, snap); + branchPlaceholder = 'Örn: ' + defaultWtBranch; + + let prefix = 'feat'; + let scope = ''; + const first = (candidateFiles[0] || '').toLowerCase(); + if (first.startsWith('internal/mcp')) { scope = '(mcp)'; prefix = 'feat'; } + else if (first.startsWith('web/')) { scope = '(ui)'; prefix = 'feat'; } + else if (first.startsWith('docs/') || first.endsWith('.md')) { scope = '(docs)'; prefix = 'docs'; } + else if (first.includes('test')) { scope = '(test)'; prefix = 'test'; } + else if (first.startsWith('.github/')) { scope = '(ci)'; prefix = 'ci'; } + + const count = candidateFiles.length; + const countLabel = count === 1 ? '1 dosya' : `${count} dosya`; + const fileSummary = candidateFiles.slice(0, 2).map((x) => x.split('/').pop()).join(', '); + const moreSuffix = count > 2 ? '...' : ''; + const desc = count > 0 ? `${countLabel} (${fileSummary}${moreSuffix}) güncellemeleri ve iyileştirmeler` : 'yeni özellik geliştirmeleri'; + + defaultCommitMsg = `${prefix}${scope}: ${desc}`; + defaultPrTitle = defaultCommitMsg; + defaultPrBody = `## Neler Değişti?\n- ${candidateFiles.slice(0, 8).map((f) => `\`${f}\` üzerinde geliştirmeler`).join('\n- ')}\n\n## Doğrulama\n- Yerel testler ve kontroller tamamlandı.`; + } + + html += ` +
+

+ 🚀 Konsolsuz Commit & PR Stüdyosu + ${secretFile ? '🛡️ Güvenlik Engeli' : (candidateFiles.length + ' Dosya Bekliyor')} +

+
+ Terminal açmadan çalışma alanındaki açık dosyaları yeni bir dala aktarabilir, commit atabilir veya doğrudan origin'e pushlayıp GitHub PR açabilirsiniz. +
+ + ${secretFile ? ` +
+ GÜVENLİK ENGELİ: '${esc(secretFile)}' dosyası gizli/hassas bilgi (secret/private key/env) olarak tespit edildi! Bu dosya güvenliğiniz için commitlenemez. +
+ ` : ''} + +
+
+ + +
+
+ +
+ ${candidateFiles.map((f) => { + const isSec = isSecretFile(f, snap); + return `${isSec ? '🛡️ ' : ''}${esc(f)}`; + }).join('')} +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + + +
+
+
+ `; + } + + if (canPromote) { + const savedDraft = state.draftPrEdits[b.name]; + const promoteTitle = savedDraft?.title ?? b.draftPrTitle ?? b.lastCommitMsg ?? ('feat: ' + b.name); + const promoteBody = savedDraft?.body ?? b.draftPrBody ?? ''; + html += ` +
+

+ 📝 Push Öncesi PR Başlık & Açıklama + Local → Remote +

+
Dalı origin’e pushlamadan önce PR başlığını ve açıklamasını burada hazırlayıp kaydedebilirsiniz.
+
+
+ + +
+
+ + +
+
+ +
+
+
+ `; + } else if (isAlreadySynced && b.hemisphere === 'lower') { + html += ` +
+

+ ✓ main Omurgası ile Senkronize + Kalıntı Dal +

+
+ Bu dal (${esc(b.name)}) GitHub main omurgasıyla tamamen eşitlendi. Push edilecek yeni bir commit veya kaydedilmemiş açık değişiklik bulunmuyor. +
+
+ ${b.isHead ? '' : ''} + +
+
+ `; + } + + if (b.changedFiles?.length) { + html += ` +
+

Değişen Dosyalar (${b.changedFiles.length})

+
+ ${b.changedFiles.map((f) => { + const special = /changelog|components\.lock|go\.mod|go\.sum|version/i.test(f); + return `${esc(f)}`; + }).join('')} +
+
+ `; + } + + if (b.pr && isOpen) { + html += ` +
+

✏️ PR #${b.pr.number} Başlık & Açıklama Düzenle

+
+ + +
+ +
+
+
+ `; + } else if (b.pr && !isOpen) { + html += ` +
+

+ 📜 PR #${b.pr.number} Detayı + ${esc(b.pr.reviewState || 'MERGED')} +

+
Başlık: ${esc(b.pr.title)}
+ ${b.pr.author ? `
Yazar: @${esc(b.pr.author)}
` : ''} + ${b.pr.body ? ` +
PR Açıklaması
+
${esc(b.pr.body)}
+ ` : '
Bu PR için GitHub açıklaması kaydedilmemiş veya gövde boş.
'} +
+ `; + } + + if (b.canAmendCommit) { + html += ` +
+

✏️ Son Commit Mesajını Değiştir (--amend --only)

+
+ +
+ +
+
+
+ `; + } + + if (b.suggestedCmd) { + html += ` +
+

+ Tek Tıkla Terminal Komutu + +

+
${esc(b.suggestedCmd)}
+
+ `; + } + + el.detail.innerHTML = html; + + if (snap.pendingProposal) { + wireProposalActions(onApplySnapshot); + } + + // Bind Event Listeners + document.getElementById('act-checkout')?.addEventListener('click', (ev) => { + if (onCheckoutBranch) onCheckoutBranch(b.id, ev.currentTarget); + }); + document.getElementById('act-checkout-main')?.addEventListener('click', (ev) => { + if (onCheckoutBranch) onCheckoutBranch('main', ev.currentTarget); + }); + document.getElementById('act-checkout-main-synced')?.addEventListener('click', (ev) => { + if (onCheckoutBranch) onCheckoutBranch('main', ev.currentTarget); + }); + document.getElementById('act-delete-synced')?.addEventListener('click', (ev) => { + if (onDeleteBranch) onDeleteBranch(b.id, ev.currentTarget); + }); + document.getElementById('act-promote')?.addEventListener('click', (ev) => { + if (onPromoteBranch) onPromoteBranch(b.id, undefined, undefined, ev.currentTarget); + }); + + const formWt = document.getElementById('form-wt-commit'); + formWt?.addEventListener('submit', (ev) => { + ev.preventDefault(); + const brName = document.getElementById('wt-branch-name').value; + const msg = document.getElementById('wt-commit-msg').value; + const prTitle = document.getElementById('wt-pr-title')?.value || ''; + const prBody = document.getElementById('wt-pr-body')?.value || ''; + const btn = document.getElementById('act-wt-commit-only'); + if (onCommitWorkingTree) onCommitWorkingTree(brName, msg, false, prTitle, prBody, btn); + }); + + document.getElementById('act-wt-commit-push')?.addEventListener('click', () => { + const brName = document.getElementById('wt-branch-name').value; + const msg = document.getElementById('wt-commit-msg').value; + const prTitle = document.getElementById('wt-pr-title')?.value || ''; + const prBody = document.getElementById('wt-pr-body')?.value || ''; + const btn = document.getElementById('act-wt-commit-push'); + if (onCommitWorkingTree) onCommitWorkingTree(brName, msg, true, prTitle, prBody, btn); + }); + + document.getElementById('act-wt-discard')?.addEventListener('click', () => { + if (onDiscardWorkingTree) onDiscardWorkingTree(); + }); + + document.getElementById('promote-pr-title')?.addEventListener('input', (ev) => { + state.draftPrEdits[b.name] = { + title: ev.target.value, + body: document.getElementById('promote-pr-body')?.value || '', + }; + }); + document.getElementById('promote-pr-body')?.addEventListener('input', (ev) => { + state.draftPrEdits[b.name] = { + title: document.getElementById('promote-pr-title')?.value || '', + body: ev.target.value, + }; + }); + document.getElementById('form-promote-pr')?.addEventListener('submit', (ev) => { + ev.preventDefault(); + const pTitle = document.getElementById('promote-pr-title').value; + const pBody = document.getElementById('promote-pr-body').value; + const btn = document.getElementById('act-promote-submit'); + if (onPromoteBranch) onPromoteBranch(b.id, pTitle, pBody, btn); + }); + + document.getElementById('merge-strategy')?.addEventListener('change', (ev) => { + state.mergeStrategy = ev.target.value; + }); + document.getElementById('act-merge')?.addEventListener('click', (ev) => { + if (onMergeBranch) onMergeBranch(b.id, ev.currentTarget); + }); + document.getElementById('act-resolve')?.addEventListener('click', () => { + if (onOpenConflictStudio) onOpenConflictStudio(b.id); + }); + document.getElementById('act-resolve-card')?.addEventListener('click', () => { + if (onOpenConflictStudio) onOpenConflictStudio(b.id); + }); + document.getElementById('act-fix-ci')?.addEventListener('click', () => { + if (onFixCI) onFixCI(b.id); + }); + document.getElementById('act-delete')?.addEventListener('click', (ev) => { + if (onDeleteBranch) onDeleteBranch(b.id, ev.currentTarget); + }); + + document.getElementById('form-edit-pr')?.addEventListener('submit', (ev) => { + ev.preventDefault(); + const title = document.getElementById('pr-edit-title').value; + const body = document.getElementById('pr-edit-body').value; + if (onEditPR) onEditPR(b.id, title, body); + }); + + document.getElementById('form-amend-commit')?.addEventListener('submit', (ev) => { + ev.preventDefault(); + const msg = document.getElementById('commit-amend-msg').value; + if (onAmendCommit) onAmendCommit(b.id, msg); + }); + + document.getElementById('act-copy-cmd')?.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(b.suggestedCmd); + showToast('Terminal komutu panoya kopyalandı', 'ok'); + } catch { + showToast('Pano izni verilemedi', 'warn'); + } + }); + + document.getElementById('act-copy-log')?.addEventListener('click', async () => { + try { + await navigator.clipboard.writeText(b.pr?.ci?.rawLog || ''); + showToast('CI hata logu panoya kopyalandı', 'ok'); + } catch { + showToast('Pano izni verilemedi; logu seçip kopyalayabilirsiniz', 'warn'); + } + }); + + document.getElementById('act-run-local')?.addEventListener('click', () => { + const cmd = b.pr?.ci?.extracts?.[0]?.reproCmd || 'go test -v ./...'; + if (onLocalTestRun) onLocalTestRun(b.id, cmd); + }); +} diff --git a/web/modules/state.js b/web/modules/state.js new file mode 100644 index 0000000..bd0557a --- /dev/null +++ b/web/modules/state.js @@ -0,0 +1,144 @@ +// web/modules/state.js - Reactive state store and cached DOM element registry + +export const state = { + snapshot: null, + selectedBranchId: null, + selectedNodeSha: null, + filter: 'all', // 'all' | 'mine' | 'issues' | 'ci_fail' | 'lower' | 'gone' + pathLens: '', + showMergedArches: true, + mergeStrategy: 'merge', + offlineMode: false, + lastSig: '', + zoom: 1, + panX: 0, + panY: 0, + panning: null, + drag: null, + localRunOutput: {}, + pendingAutoMerge: {}, + autoMergingInFlight: {}, + draftPrEdits: {}, + studio: null, + clientLogs: [], +}; + +// Cached DOM element lookup helper +export const el = {}; + +export function initElements() { + const ids = [ + 'rail-svg', 'svg-viewport', 'repo-select', 'mode-badge', 'kpi-pills', + 'radar-list', 'radar-count', 'bottom-dock', 'dock-tab-radar', 'dock-tab-logs', + 'dock-tab-actions', 'dock-radar-count', 'dock-log-count', 'dock-action-count', + 'dock-toggle-btn', 'dock-clear-btn', 'dock-pane-radar', 'dock-pane-logs', + 'dock-pane-actions', 'dock-logs-stream', 'dock-actions-stream', 'inspector-detail', + 'prune-count', 'drag-hint', 'spine-sync-badge', 'engineStatus', 'zoom-reset', + 'toggle-merged-arches', 'create-branch-modal', 'new-branch-form', 'new-branch-name', + 'new-branch-base', 'toast-stack', 'conflict-studio-modal', 'studio-branch-badge', + 'studio-file-tabs', 'studio-guide-box', 'studio-guide-text', 'studio-strategy-bar', + 'studio-line-badge', 'studio-mode-badge', 'studio-left-conflict', 'studio-right-preview', + 'studio-error-banner', 'studio-error-text', 'studio-run-vet', 'studio-apply', + 'mcp-connect-modal', 'mcp-config-snippet', 'btn-logs-modal', 'log-count', + 'logs-modal', 'logs-list', 'btn-protect-branch', 'btn-update-check', + 'lens-path-input', 'perf-cache-badge', 'security-update-modal', 'sec-prot-badge', + 'sec-prot-summary', 'btn-enable-protection', 'sec-team-chip', 'sec-update-status', + 'sec-update-cmd', 'btn-add-project', 'btn-remove-project', 'add-project-modal', + 'add-project-form', 'project-path-input', 'project-name-input', 'add-proj-close', + 'add-proj-cancel', 'btn-start-tour', 'tour-backdrop', 'tour-card', + 'tour-step-badge', 'tour-step-title', 'tour-step-body', 'tour-prev-btn', + 'tour-next-btn', 'tour-dots', 'tour-close-btn' + ]; + + ids.forEach((id) => { + // Convert kebab-case to camelCase for el map (e.g. 'rail-svg' -> 'svg', 'inspector-detail' -> 'detail') + const dom = document.getElementById(id); + el[id] = dom; + }); + + // Semantic alias mappings to match existing codebase conventions + el.svg = el['rail-svg']; + el.viewport = el['svg-viewport']; + el.repoSelect = el['repo-select']; + el.modeBadge = el['mode-badge']; + el.kpiPills = el['kpi-pills']; + el.radarList = el['radar-list']; + el.radarCount = el['radar-count']; + el.dock = el['bottom-dock']; + el.dockTabRadar = el['dock-tab-radar']; + el.dockTabLogs = el['dock-tab-logs']; + el.dockTabActions = el['dock-tab-actions']; + el.dockRadarCount = el['dock-radar-count']; + el.dockLogCount = el['dock-log-count']; + el.dockActionCount = el['dock-action-count']; + el.dockToggleBtn = el['dock-toggle-btn']; + el.dockClearBtn = el['dock-clear-btn']; + el.dockPaneRadar = el['dock-pane-radar']; + el.dockPaneLogs = el['dock-pane-logs']; + el.dockPaneActions = el['dock-pane-actions']; + el.dockLogsStream = el['dock-logs-stream']; + el.dockActionsStream = el['dock-actions-stream']; + el.detail = el['inspector-detail']; + el.pruneCount = el['prune-count']; + el.dragHint = el['drag-hint']; + el.spineSyncBadge = el['spine-sync-badge']; + el.engineStatus = document.getElementById('engine-status') || el['engineStatus']; + el.zoomReset = el['zoom-reset']; + el.toggleMerged = el['toggle-merged-arches']; + el.modal = el['create-branch-modal']; + el.newBranchForm = el['new-branch-form']; + el.newBranchName = el['new-branch-name']; + el.newBranchBase = el['new-branch-base']; + el.toastStack = el['toast-stack']; + el.conflictStudioModal = el['conflict-studio-modal']; + el.studioBranchBadge = el['studio-branch-badge']; + el.studioFileTabs = el['studio-file-tabs']; + el.studioGuideBox = el['studio-guide-box']; + el.studioGuideText = el['studio-guide-text']; + el.studioStrategyBar = el['studio-strategy-bar']; + el.studioLineBadge = el['studio-line-badge']; + el.studioModeBadge = el['studio-mode-badge']; + el.studioLeftConflict = el['studio-left-conflict']; + el.studioRightPreview = el['studio-right-preview']; + el.studioErrorBanner = el['studio-error-banner']; + el.studioErrorText = el['studio-error-text']; + el.studioRunVet = el['studio-run-vet']; + el.studioApplyBtn = el['studio-apply']; + el.mcpModal = el['mcp-connect-modal']; + el.mcpConfigSnippet = el['mcp-config-snippet']; + el.btnLogsModal = el['btn-logs-modal']; + el.logCount = el['log-count']; + el.logsModal = el['logs-modal']; + el.logsList = el['logs-list']; + el.btnProtectBranch = el['btn-protect-branch']; + el.btnUpdateCheck = el['btn-update-check']; + el.lensPathInput = el['lens-path-input']; + el.perfCacheBadge = el['perf-cache-badge']; + el.securityUpdateModal = el['security-update-modal']; + el.secProtBadge = el['sec-prot-badge']; + el.secProtSummary = el['sec-prot-summary']; + el.btnEnableProtection = el['btn-enable-protection']; + el.secTeamChip = el['sec-team-chip']; + el.secUpdateStatus = el['sec-update-status']; + el.secUpdateCmd = el['sec-update-cmd']; + el.btnAddProject = el['btn-add-project']; + el.btnRemoveProject = el['btn-remove-project']; + el.addProjectModal = el['add-project-modal']; + el.addProjectForm = el['add-project-form']; + el.projectPathInput = el['project-path-input']; + el.projectNameInput = el['project-name-input']; + el.addProjClose = el['add-proj-close']; + el.addProjCancel = el['add-proj-cancel']; + el.btnStartTour = el['btn-start-tour']; + el.tourBackdrop = el['tour-backdrop']; + el.tourCard = el['tour-card']; + el.tourStepBadge = el['tour-step-badge']; + el.tourStepTitle = el['tour-step-title']; + el.tourStepBody = el['tour-step-body']; + el.tourPrevBtn = el['tour-prev-btn']; + el.tourNextBtn = el['tour-next-btn']; + el.tourDots = el['tour-dots']; + el.tourCloseBtn = el['tour-close-btn']; + + return el; +} diff --git a/web/modules/utils.js b/web/modules/utils.js new file mode 100644 index 0000000..ca539bc --- /dev/null +++ b/web/modules/utils.js @@ -0,0 +1,215 @@ +// web/modules/utils.js - Shared formatting, DOM, security and naming helpers +import { SVG_NS } from './constants.js'; + +export function esc(str) { + return String(str ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); +} + +export function truncate(str, max) { + if (!str) return ''; + return str.length > max ? str.slice(0, max - 1) + '…' : str; +} + +export function timeAgo(isoOrDate) { + if (!isoOrDate) return '—'; + const d = new Date(isoOrDate); + if (isNaN(d.getTime())) return String(isoOrDate); + const sec = Math.floor((Date.now() - d.getTime()) / 1000); + if (sec < 5) return 'az önce'; + if (sec < 60) return `${sec} sn önce`; + const min = Math.floor(sec / 60); + if (min < 60) return `${min} dk önce`; + const hr = Math.floor(min / 60); + if (hr < 24) return `${hr} sa önce`; + const day = Math.floor(hr / 24); + return `${day} gün önce`; +} + +export function showToast(msg, tone = 'ok') { + const stack = document.getElementById('toast-stack'); + if (!stack) return; + const t = document.createElement('div'); + t.className = `toast ${tone}`; + t.title = 'Metni panoya kopyalamak için tıklayın'; + t.textContent = msg; + t.addEventListener('click', () => { + navigator.clipboard?.writeText(msg).catch(() => {}); + t.classList.add('fade-out'); + setTimeout(() => t.remove(), 180); + }); + stack.appendChild(t); + const timeoutMs = tone === 'danger' ? 7500 : 3200; + setTimeout(() => { + t.classList.add('fade-out'); + setTimeout(() => t.remove(), 260); + }, timeoutMs); +} + +export async function runWithBtnBusy(btnEl, busyText, fn) { + if (!btnEl) return await fn(); + const origText = btnEl.innerHTML; + btnEl.disabled = true; + btnEl.classList.add('btn-busy'); + btnEl.textContent = busyText || '⏳ İşleniyor...'; + + const statusEl = document.getElementById('engine-status'); + const origStatus = statusEl ? statusEl.textContent : ''; + if (statusEl) { + statusEl.textContent = '● Git İşlemi Yürütülüyor...'; + statusEl.classList.add('running-pulse'); + } + + try { + return await fn(); + } finally { + btnEl.disabled = false; + btnEl.classList.remove('btn-busy'); + btnEl.innerHTML = origText; + if (statusEl) { + statusEl.textContent = origStatus || '● Hazır'; + statusEl.classList.remove('running-pulse'); + } + } +} + +export function svgEl(tag, attrs = {}, text = null) { + const node = document.createElementNS(SVG_NS, tag); + for (const [k, v] of Object.entries(attrs)) { + if (v !== undefined && v !== null) { + node.setAttribute(k, String(v)); + } + } + if (text !== null) { + node.textContent = text; + } + return node; +} + +export function isMergedOrGone(b) { + return Boolean(b.state === 'merged' || b.state === 'gone' || b.originGone); +} + +export function isOpenPR(b) { + return Boolean(b.pr && b.pr.number > 0 && b.state === 'open' && b.pr.reviewState !== 'MERGED'); +} + +export function isLocalOpen(b) { + return Boolean(b.hasLocal && b.state === 'open' && !isMergedOrGone(b)); +} + +export function isMyBranch(b, currentUser = '') { + const me = (currentUser || '').trim().toLowerCase(); + if (!me) return Boolean(b.isHead); + const bAuth = (b.author || '').trim().toLowerCase(); + const prAuth = (b.pr?.author || '').trim().toLowerCase(); + return bAuth === me || prAuth === me || Boolean(b.isHead); +} + +export function isSecretFile(f, snap = null) { + if (!f) return false; + const patterns = snap?.repo?.secretPatterns || [ + 'img/logoyeni.jpg', + 'referans/**', + 'referans/*', + 'referans', + '.mcp.json', + '.env*', + '*.env', + '*.pem', + '*.key', + 'id_*', + 'id_rsa*', + 'id_ed25519*', + ]; + const clean = f.replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase(); + const base = clean.split('/').pop(); + + for (const p of patterns) { + const pClean = p.replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase(); + if (pClean.endsWith('/**') || pClean.endsWith('/*')) { + const prefix = pClean.replace(/\/\*\*?$/, ''); + if (clean === prefix || clean.startsWith(prefix + '/')) return true; + } else if (pClean.endsWith('/')) { + if (clean.startsWith(pClean)) return true; + } else if (clean === pClean) { + return true; + } + if (!pClean.includes('/')) { + if (pClean.includes('*')) { + const reg = new RegExp('^' + pClean.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$'); + if (reg.test(base)) return true; + } else if (base === pClean) { + return true; + } + } + if (pClean.includes('*')) { + const reg = new RegExp('^' + pClean.replace(/\./g, '\\.').replace(/\*/g, '.*') + '$'); + if (reg.test(clean)) return true; + } + } + return false; +} + +export function suggestUniqueBranchName(arg1, arg2, arg3) { + let prefix = 'feat'; + let files = []; + let snap = null; + if (typeof arg1 === 'string') { + prefix = arg1; + files = Array.isArray(arg2) ? arg2 : []; + snap = arg3; + } else if (arg1 && typeof arg1 === 'object') { + files = arg1.changedFiles || []; + snap = arg2; + } + let slug = 'new-feature'; + if (files.length > 0) { + const first = (files[0] || '').toLowerCase(); + if (first.endsWith('.md') || first.startsWith('docs/')) { + prefix = 'docs'; + } else if (first.includes('test')) { + prefix = 'test'; + } else if (first.endsWith('.css') || first.endsWith('.html')) { + prefix = 'style'; + } else if (first.includes('gitignore') || first.endsWith('.json') || first.endsWith('.lock') || first.endsWith('.yml') || first.endsWith('.yaml')) { + prefix = 'chore'; + } + const rawBase = first.split('/').pop().replace(/^\./, '').replace(/\.[^.]+$/, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''); + if (rawBase && rawBase !== 'index' && rawBase !== 'main') { + slug = `${rawBase}-guncel`; + } + } + const candidateBase = `${prefix}/${slug}`.slice(0, 40); + const existing = new Set((snap?.branches || []).map((x) => (x.name || '').toLowerCase())); + if (!existing.has(candidateBase)) { + return candidateBase; + } + const shortSha = (snap?.nodes?.[snap.nodes.length - 1]?.shortSha || '').slice(0, 5); + if (shortSha && !existing.has(`${candidateBase}-${shortSha}`.toLowerCase())) { + return `${candidateBase}-${shortSha}`; + } + let n = 2; + while (existing.has(`${candidateBase}-${n}`)) { + n++; + } + return `${candidateBase}-${n}`; +} + +export function snapshotSignature(snap) { + if (!snap) return ''; + const r = snap.repo || {}; + const lastNode = snap.nodes?.[snap.nodes.length - 1]?.shortSha || ''; + const bSig = (snap.branches || []).map((b) => [ + b.id, b.state, b.hemisphere, b.isHead ? 1 : 0, b.hasLocal ? 1 : 0, b.aheadMain, b.behindMain, + b.uncommittedCount, b.lastCommitMsg, b.draftPrTitle || '', b.draftPrBody || '', + (b.changedFiles || []).length, b.originGone ? 1 : 0, + b.pr?.title || '', b.pr?.body || '', b.pr?.ci?.state || '', b.pr?.ci?.duration || '', + b.conflict?.hasConflict ? 1 : 0, + ].join('|')).join(';'); + const logSig = `${snap.logs?.length || 0}:${snap.logs?.[0]?.id || ''}`; + return `${r.id}:${r.ahead}:${r.behind}:${r.dirtyCount}:${snap.nodes?.length || 0}:${lastNode}:${bSig}:${logSig}`; +}