From eda9ac75a40d242469fdcd4d078c4bc665ff2c8f Mon Sep 17 00:00:00 2001 From: Willie Date: Fri, 29 May 2026 20:26:00 +0800 Subject: [PATCH] feat(git-root): guard root scope against submodule traps and config leaks At the root git_root scope, `git add -A` over the config base directory records any subdirectory that has its own .git (e.g. the skills source) as an empty submodule, and can commit the machine-specific config.yaml. - Detect nested repos and warn before commit/push (CLI) or surface them on the Git Sync page with a one-click "Disable nested .git" action (UI), which renames .git to .git.disabled (reversible) and drops any stale gitlink from the index so the directory's files track as normal blobs. - Keep config.yaml out of a root-scope repo automatically: ensure it is ignored and untrack it (git rm --cached) before staging, on both the CLI and the web UI commit/push paths. - Expose nestedRepos/configTracked in GET /api/git/status and add POST /api/git/absorb-nested (validated against detected nested repos). --- cmd/skillshare/commit.go | 6 ++ cmd/skillshare/gitroot.go | 53 ++++++++++++ cmd/skillshare/push.go | 6 ++ internal/git/scope.go | 137 +++++++++++++++++++++++++++++++ internal/git/scope_test.go | 144 +++++++++++++++++++++++++++++++++ internal/server/handler_git.go | 89 ++++++++++++++++++++ internal/server/server.go | 1 + ui/src/api/client.ts | 8 ++ ui/src/i18n/locales/de.json | 5 ++ ui/src/i18n/locales/en.json | 5 ++ ui/src/i18n/locales/es.json | 5 ++ ui/src/i18n/locales/fa.json | 5 ++ ui/src/i18n/locales/fr.json | 5 ++ ui/src/i18n/locales/id.json | 5 ++ ui/src/i18n/locales/ja.json | 5 ++ ui/src/i18n/locales/ko.json | 5 ++ ui/src/i18n/locales/pt-BR.json | 5 ++ ui/src/i18n/locales/zh-CN.json | 5 ++ ui/src/i18n/locales/zh-TW.json | 5 ++ ui/src/pages/GitSyncPage.tsx | 47 +++++++++++ 20 files changed, 546 insertions(+) diff --git a/cmd/skillshare/commit.go b/cmd/skillshare/commit.go index 12ef48142..3e96e5b16 100644 --- a/cmd/skillshare/commit.go +++ b/cmd/skillshare/commit.go @@ -49,6 +49,12 @@ func cmdCommit(args []string) error { return nil // Error already displayed } + if sweep := rootScopeSafetySweep(cfg, source); sweep.hasNotice() { + spinner.Stop() + sweep.printNotices(source) + spinner = ui.StartSpinner("Checking changes...") + } + changes, err := getGitChanges(source) if err != nil { spinner.Fail("Failed to check git status") diff --git a/cmd/skillshare/gitroot.go b/cmd/skillshare/gitroot.go index ee7e13ce0..b51573ac4 100644 --- a/cmd/skillshare/gitroot.go +++ b/cmd/skillshare/gitroot.go @@ -1,10 +1,12 @@ package main import ( + "fmt" "os" "path/filepath" "skillshare/internal/config" + gitops "skillshare/internal/git" "skillshare/internal/ui" ) @@ -41,3 +43,54 @@ func resolveGitRoot(cfg *config.Config, spinner *ui.Spinner) (string, bool) { } return root, true } + +// rootSweepResult reports what the root-scope safety sweep changed or found. +type rootSweepResult struct { + configUntracked bool // config.yaml was removed from version control + nested []string // subdirs (relative) that have their own .git +} + +func (r rootSweepResult) hasNotice() bool { + return r.configUntracked || len(r.nested) > 0 +} + +// rootScopeSafetySweep guards a root-scope repo before staging. It keeps +// skillshare's own config.yaml out of version control (the push-time net for +// repos not created via InitScopeRepo) and detects nested git repos that would +// otherwise be committed as empty submodules. It is a no-op (zero result) for +// non-root scopes. Mutation failures are swallowed: the worst case is the prior +// behavior, never a blocked push. +func rootScopeSafetySweep(cfg *config.Config, dir string) rootSweepResult { + var res rootSweepResult + if cfg.GitRoot != "root" { + return res + } + if removed, err := gitops.EnsureConfigUntracked(dir); err == nil { + res.configUntracked = removed + } + if nested, err := gitops.NestedRepos(dir); err == nil { + res.nested = nested + } + return res +} + +// printNotices reports the sweep outcome. Callers stop any active spinner first +// so the warning box renders cleanly. +func (r rootSweepResult) printNotices(dir string) { + if r.configUntracked { + ui.Info("Removed config.yaml from version control (kept on disk; it holds machine-specific paths)") + } + if len(r.nested) > 0 { + lines := []string{"These directories have their own .git and upload as EMPTY submodules:"} + for _, sub := range r.nested { + lines = append(lines, " - "+sub) + } + lines = append(lines, + "", + "Their files will NOT be tracked. Disable each nested repo, then push again:", + fmt.Sprintf(" mv %s//.git %s//.git.disabled", dir, dir), + "(or use one-click disable on the web UI Git Sync page)", + ) + ui.WarningBox("Nested git repositories found", lines...) + } +} diff --git a/cmd/skillshare/push.go b/cmd/skillshare/push.go index 53966aa78..5c9abfce6 100644 --- a/cmd/skillshare/push.go +++ b/cmd/skillshare/push.go @@ -236,6 +236,12 @@ func cmdPush(args []string) error { return nil // Error already displayed } + if sweep := rootScopeSafetySweep(cfg, source); sweep.hasNotice() { + spinner.Stop() + sweep.printNotices(source) + spinner = ui.StartSpinner("Checking changes...") + } + changes, err := getGitChanges(source) if err != nil { spinner.Fail("Failed to check git status") diff --git a/internal/git/scope.go b/internal/git/scope.go index 43be1e791..d6e86a05d 100644 --- a/internal/git/scope.go +++ b/internal/git/scope.go @@ -1,9 +1,12 @@ package git import ( + "fmt" + "io/fs" "os" "os/exec" "path/filepath" + "sort" "strings" ) @@ -90,3 +93,137 @@ func InitScopeRepo(dir, scope string) (identitySet bool, err error) { } return EnsureLocalIdentity(dir) } + +// ensureGitignoreEntry appends entry as a line to dir/.gitignore when absent, +// creating the file if needed. It is the single-entry counterpart to +// WriteScopeGitignore and is idempotent. +func ensureGitignoreEntry(dir, entry string) error { + gitignore := filepath.Join(dir, ".gitignore") + existing, err := os.ReadFile(gitignore) + if err != nil { + if os.IsNotExist(err) { + return os.WriteFile(gitignore, []byte(entry+"\n"), 0o644) + } + return err + } + if gitignoreHasEntry(string(existing), entry) { + return nil + } + content := string(existing) + if content != "" && !strings.HasSuffix(content, "\n") { + content += "\n" + } + content += entry + "\n" + return os.WriteFile(gitignore, []byte(content), 0o644) +} + +// IsConfigTracked reports whether config.yaml is tracked in the repo at dir. +// Used by the web UI to warn that a root-scope repo is versioning the +// machine-specific config.yaml. +func IsConfigTracked(dir string) bool { + return isTracked(dir, "config.yaml") +} + +// isTracked reports whether path (relative to dir) is tracked in the repo at dir. +func isTracked(dir, path string) bool { + cmd := exec.Command("git", "ls-files", "--", path) + cmd.Dir = dir + out, err := cmd.Output() + return err == nil && strings.TrimSpace(string(out)) != "" +} + +// EnsureConfigUntracked keeps skillshare's own config.yaml out of a root-scope +// repo: it ensures config.yaml is in .gitignore and, if the file is already +// tracked, removes it from the index with `git rm --cached` (the file stays on +// disk). Returns removed=true only when an actually-tracked config.yaml was +// untracked. This is the push-time safety net for repos created outside +// InitScopeRepo (manual `git_root: root` edits, externally-initialized repos, or +// a config.yaml committed before switching to root scope), where the init-time +// .gitignore guarantee does not apply. +func EnsureConfigUntracked(dir string) (removed bool, err error) { + if err := ensureGitignoreEntry(dir, "config.yaml"); err != nil { + return false, err + } + if !isTracked(dir, "config.yaml") { + return false, nil + } + cmd := exec.Command("git", "rm", "--cached", "--", "config.yaml") + cmd.Dir = dir + if err := cmd.Run(); err != nil { + return false, fmt.Errorf("untrack config.yaml: %w", err) + } + return true, nil +} + +// NestedRepos returns subdirectories of dir (relative paths, excluding dir +// itself) that contain their own .git. Git records such directories as gitlinks +// (submodules) on commit, silently dropping all of their files — so callers warn +// about them before staging a root-scope repo. The walk prunes at each match and +// skips .git / .git.disabled internals; results are sorted. +func NestedRepos(dir string) ([]string, error) { + root := filepath.Clean(dir) + found := make([]string, 0) + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, walkErr error) error { + if walkErr != nil || !d.IsDir() { + return nil //nolint:nilerr // skip unreadable entries, keep walking + } + if path == root { + return nil // the scope repo's own .git is not "nested" + } + if name := d.Name(); name == ".git" || name == ".git.disabled" { + return filepath.SkipDir + } + if _, statErr := os.Stat(filepath.Join(path, ".git")); statErr == nil { + rel, _ := filepath.Rel(root, path) + found = append(found, rel) + return filepath.SkipDir // don't descend into a nested repo + } + return nil + }) + sort.Strings(found) + return found, err +} + +// DisableNestedRepo neutralizes a nested git repo at dir/sub by renaming its +// .git to .git.disabled (reversible: rename back to re-enable) and ensuring +// .git.disabled is gitignored so the disabled internals are never committed. +// It refuses to clobber an existing .git.disabled. +func DisableNestedRepo(dir, sub string) error { + gitDir := filepath.Join(dir, sub, ".git") + disabled := filepath.Join(dir, sub, ".git.disabled") + if _, err := os.Stat(gitDir); err != nil { + return fmt.Errorf("%s has no nested .git", sub) + } + if _, err := os.Stat(disabled); err == nil { + return fmt.Errorf("%s/.git.disabled already exists; resolve it manually", sub) + } + if err := os.Rename(gitDir, disabled); err != nil { + return err + } + if err := ensureGitignoreEntry(dir, ".git.disabled"); err != nil { + return err + } + // If the parent repo already committed as a gitlink (160000), renaming + // .git is not enough: the stale gitlink stays in the index and `git add -A` + // won't deconvert it. Drop the index entry so the directory's files are + // re-tracked as blobs on the next add. Best-effort: a repo that never + // committed the gitlink has no such entry. + if IsRepo(dir) && isGitlink(dir, sub) { + cmd := exec.Command("git", "rm", "--cached", "-q", "--", sub) + cmd.Dir = dir + _ = cmd.Run() + } + return nil +} + +// isGitlink reports whether the repo at dir records sub as a gitlink (an +// embedded submodule pointer, index mode 160000) rather than tracked files. +func isGitlink(dir, sub string) bool { + cmd := exec.Command("git", "ls-files", "-s", "--", sub) + cmd.Dir = dir + out, err := cmd.Output() + if err != nil { + return false + } + return strings.HasPrefix(strings.TrimSpace(string(out)), "160000") +} diff --git a/internal/git/scope_test.go b/internal/git/scope_test.go index 4d0117f4f..06160d7f7 100644 --- a/internal/git/scope_test.go +++ b/internal/git/scope_test.go @@ -2,6 +2,7 @@ package git import ( "os" + "os/exec" "path/filepath" "strings" "testing" @@ -69,3 +70,146 @@ func TestWriteScopeGitignore_IdempotentAtRoot(t *testing.T) { t.Errorf("config.yaml must appear exactly once, got %d:\n%s", n, got) } } + +func gitExec(t *testing.T, dir string, args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), + "GIT_AUTHOR_NAME=test", "GIT_AUTHOR_EMAIL=test@test.com", + "GIT_COMMITTER_NAME=test", "GIT_COMMITTER_EMAIL=test@test.com", + ) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } +} + +func TestNestedRepos_DetectsSubdirGitOnly(t *testing.T) { + dir := t.TempDir() + mustMkdir := func(p string) { + if err := os.MkdirAll(filepath.Join(dir, p), 0o755); err != nil { + t.Fatal(err) + } + } + mustMkdir(".git") // the scope repo's own .git — must be ignored + mustMkdir("skills/.git") // a nested repo — must be detected + mustMkdir("old/.git.disabled") // already disabled — must be ignored + mustMkdir("plain/references") // a plain skill dir — must be ignored + + got, err := NestedRepos(dir) + if err != nil { + t.Fatal(err) + } + if len(got) != 1 || got[0] != "skills" { + t.Errorf("want [skills], got %v", got) + } +} + +func TestEnsureConfigUntracked_RemovesTrackedConfig(t *testing.T) { + dir := t.TempDir() + gitExec(t, dir, "init") + gitExec(t, dir, "config", "user.email", "t@t.com") + gitExec(t, dir, "config", "user.name", "t") + cfgPath := filepath.Join(dir, "config.yaml") + if err := os.WriteFile(cfgPath, []byte("k: v\n"), 0o644); err != nil { + t.Fatal(err) + } + gitExec(t, dir, "add", "config.yaml") + gitExec(t, dir, "commit", "-m", "leak config") + + removed, err := EnsureConfigUntracked(dir) + if err != nil { + t.Fatal(err) + } + if !removed { + t.Error("expected removed=true for a tracked config.yaml") + } + if isTracked(dir, "config.yaml") { + t.Error("config.yaml must no longer be tracked") + } + if _, err := os.Stat(cfgPath); err != nil { + t.Error("config.yaml file must remain on disk after untracking") + } + if gi := readGitignore(t, dir); !strings.Contains(gi, "config.yaml") { + t.Errorf(".gitignore must contain config.yaml, got:\n%s", gi) + } + if removed, _ := EnsureConfigUntracked(dir); removed { + t.Error("second call must be a no-op (removed=false)") + } +} + +func TestDisableNestedRepo_RenamesAndRefusesClobber(t *testing.T) { + dir := t.TempDir() + subGit := filepath.Join(dir, "skills", ".git") + if err := os.MkdirAll(subGit, 0o755); err != nil { + t.Fatal(err) + } + + if err := DisableNestedRepo(dir, "skills"); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(subGit); !os.IsNotExist(err) { + t.Error("skills/.git must be renamed away") + } + if _, err := os.Stat(filepath.Join(dir, "skills", ".git.disabled")); err != nil { + t.Error("skills/.git.disabled must exist after disabling") + } + if gi := readGitignore(t, dir); !strings.Contains(gi, ".git.disabled") { + t.Errorf(".gitignore must contain .git.disabled, got:\n%s", gi) + } + + // A re-created .git plus an existing .git.disabled must not be clobbered. + if err := os.MkdirAll(subGit, 0o755); err != nil { + t.Fatal(err) + } + if err := DisableNestedRepo(dir, "skills"); err == nil { + t.Error("expected an error when .git.disabled already exists") + } +} + +// TestDisableNestedRepo_DropsStaleGitlink covers the already-broken repair case: +// a parent repo that already committed the nested directory as a gitlink (the +// real-world symptom). Disabling must drop the stale gitlink so a subsequent +// `git add -A` re-tracks the directory's files as blobs instead of leaving an +// empty submodule. +func TestDisableNestedRepo_DropsStaleGitlink(t *testing.T) { + dir := t.TempDir() + gitExec(t, dir, "init") + gitExec(t, dir, "config", "user.email", "t@t.com") + gitExec(t, dir, "config", "user.name", "t") + + // A nested repo with a file, then commit it from the parent — this records + // "skills" as a gitlink (160000) in the parent index. + sub := filepath.Join(dir, "skills") + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatal(err) + } + gitExec(t, sub, "init") + gitExec(t, sub, "config", "user.email", "t@t.com") + gitExec(t, sub, "config", "user.name", "t") + if err := os.WriteFile(filepath.Join(sub, "SKILL.md"), []byte("# skill\n"), 0o644); err != nil { + t.Fatal(err) + } + gitExec(t, sub, "add", "-A") + gitExec(t, sub, "commit", "-m", "nested") + gitExec(t, dir, "add", "skills") + gitExec(t, dir, "commit", "-m", "record gitlink") + + if !isGitlink(dir, "skills") { + t.Fatal("setup failed: skills should be a gitlink before disabling") + } + + if err := DisableNestedRepo(dir, "skills"); err != nil { + t.Fatal(err) + } + if isGitlink(dir, "skills") { + t.Error("stale gitlink must be dropped from the index after disabling") + } + + // After re-staging, the directory's files are tracked as blobs. + gitExec(t, dir, "add", "-A") + out, err := exec.Command("git", "-C", dir, "ls-files", "skills/SKILL.md").Output() + if err != nil || strings.TrimSpace(string(out)) == "" { + t.Errorf("skills/SKILL.md must be tracked as a file after disabling, got %q (err %v)", out, err) + } +} diff --git a/internal/server/handler_git.go b/internal/server/handler_git.go index 3547f4b4a..e8e5d52cd 100644 --- a/internal/server/handler_git.go +++ b/internal/server/handler_git.go @@ -27,6 +27,11 @@ type gitStatusResponse struct { HeadHash string `json:"headHash,omitempty"` HeadMessage string `json:"headMessage,omitempty"` TrackingBranch string `json:"trackingBranch,omitempty"` + // Root-scope hazards (populated only when scope == "root"): NestedRepos are + // subdirectories with their own .git that commit as empty submodules; + // ConfigTracked means config.yaml leaked into version control. + NestedRepos []string `json:"nestedRepos"` + ConfigTracked bool `json:"configTracked"` } // handleGitStatus returns the git status of the source directory @@ -48,6 +53,7 @@ func (s *Server) handleGitStatus(w http.ResponseWriter, r *http.Request) { MismatchScope: mScope, MismatchDir: mDir, Files: make([]string, 0), + NestedRepos: make([]string, 0), } // Without git on PATH every other probe is a raw exec failure; report it @@ -93,6 +99,14 @@ func (s *Server) handleGitStatus(w http.ResponseWriter, r *http.Request) { resp.TrackingBranch = tb } + // Root-scope hazards: nested submodule traps and a leaked config.yaml. + if scope == "root" { + if nested, err := git.NestedRepos(src); err == nil { + resp.NestedRepos = nested + } + resp.ConfigTracked = git.IsConfigTracked(src) + } + writeJSON(w, resp) } @@ -333,6 +347,8 @@ func (s *Server) handleGitCommit(w http.ResponseWriter, r *http.Request) { return } + s.protectRootScopeConfig(src) + status, err := git.GetStatus(src) if err != nil { writeError(w, http.StatusInternalServerError, "failed to get git status: "+err.Error()) @@ -404,6 +420,8 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) { return } + s.protectRootScopeConfig(src) + // Check for changes status, err := git.GetStatus(src) if err != nil { @@ -461,6 +479,77 @@ func (s *Server) handlePush(w http.ResponseWriter, r *http.Request) { writeJSON(w, pushResponse{Success: true, Message: "pushed successfully"}) } +// protectRootScopeConfig keeps config.yaml out of a root-scope repo before +// staging (server-side parity with the CLI push sweep). No-op off the root +// scope; best-effort so a failure never blocks the commit/push. +func (s *Server) protectRootScopeConfig(src string) { + if s.cfg.GitRoot != "root" { + return + } + _, _ = git.EnsureConfigUntracked(src) +} + +type absorbNestedRequest struct { + Subdirs []string `json:"subdirs"` +} + +// handleAbsorbNested disables nested git repos under the root scope by renaming +// each /.git to /.git.disabled, so the directory's files get tracked +// normally instead of as an empty submodule. Global mode + root scope only; each +// subdir must match a currently-detected nested repo (this also blocks path +// traversal). +func (s *Server) handleAbsorbNested(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + if s.IsProjectMode() { + writeError(w, http.StatusBadRequest, "git_root is only available in global mode") + return + } + + var body absorbNestedRequest + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + if len(body.Subdirs) == 0 { + writeError(w, http.StatusBadRequest, "no subdirectories specified") + return + } + + s.mu.Lock() + defer s.mu.Unlock() + + if s.cfg.GitRoot != "root" { + writeError(w, http.StatusBadRequest, "nested repos can only be disabled at the root scope") + return + } + src := s.cfg.EffectiveGitRoot() + + allowed := make(map[string]bool) + if nested, err := git.NestedRepos(src); err == nil { + for _, n := range nested { + allowed[n] = true + } + } + + disabled := make([]string, 0, len(body.Subdirs)) + for _, sub := range body.Subdirs { + if !allowed[sub] { + writeError(w, http.StatusBadRequest, "not a detected nested repository: "+sub) + return + } + if err := git.DisableNestedRepo(src, sub); err != nil { + writeError(w, http.StatusInternalServerError, "failed to disable "+sub+": "+err.Error()) + return + } + disabled = append(disabled, sub) + } + + s.writeOpsLog("git-absorb-nested", "ok", start, map[string]any{"subdirs": disabled}, "") + + writeJSON(w, map[string]any{"success": true, "disabled": disabled}) +} + type pullResponse struct { Success bool `json:"success"` UpToDate bool `json:"upToDate"` diff --git a/internal/server/server.go b/internal/server/server.go index 738abe6a4..7a5d342db 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -471,6 +471,7 @@ func (s *Server) registerRoutes() { s.mux.HandleFunc("GET /api/git/branches", s.handleGitBranches) s.mux.HandleFunc("POST /api/git/checkout", s.handleGitCheckout) s.mux.HandleFunc("POST /api/git/commit", s.handleGitCommit) + s.mux.HandleFunc("POST /api/git/absorb-nested", s.handleAbsorbNested) s.mux.HandleFunc("POST /api/push", s.handlePush) s.mux.HandleFunc("POST /api/pull", s.handlePull) diff --git a/ui/src/api/client.ts b/ui/src/api/client.ts index fa6452640..5bc0d3a57 100644 --- a/ui/src/api/client.ts +++ b/ui/src/api/client.ts @@ -635,6 +635,11 @@ export const api = { method: 'POST', body: JSON.stringify({ branch }), }), + gitAbsorbNested: (subdirs: string[]) => + apiFetch<{ success: boolean; disabled: string[] }>('/git/absorb-nested', { + method: 'POST', + body: JSON.stringify({ subdirs }), + }), gitCommit: (opts: { message?: string; dryRun?: boolean }) => apiFetch('/git/commit', { method: 'POST', @@ -1066,6 +1071,9 @@ export interface GitStatus { headHash?: string; headMessage?: string; trackingBranch?: string; + // Root-scope hazards (populated only when scope === 'root'). + nestedRepos: string[]; + configTracked: boolean; } export interface GitBranches { diff --git a/ui/src/i18n/locales/de.json b/ui/src/i18n/locales/de.json index 4e05a6074..bca04695c 100644 --- a/ui/src/i18n/locales/de.json +++ b/ui/src/i18n/locales/de.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "Git-Repository initialisieren", "gitSync.scope.initTitle": "Git-Repository initialisieren?", "gitSync.scope.initMessage": "Initialisiert ein Git-Repository im Bereich \"{scope}\" und stellt es ab sofort unter Versionskontrolle. Der Bereich \"root\" versioniert skills, agents und extras zusammen.", + "gitSync.nested.title": "Root-Scope: Aktion erforderlich", + "gitSync.nested.hint": "Diese Verzeichnisse haben ein eigenes .git und würden als leere Submodule hochgeladen – ihre Dateien werden nicht versioniert. Deaktivieren benennt .git in .git.disabled um (umkehrbar), damit die Dateien normal versioniert werden.", + "gitSync.nested.disableButton": "Verschachteltes .git deaktivieren", + "gitSync.nested.disabled": "Verschachteltes Repository deaktiviert: {dirs}", + "gitSync.nested.configTracked": "config.yaml wird in diesem Repository versioniert. Es wird beim nächsten Commit oder Push automatisch aus der Versionsverwaltung entfernt; die Datei bleibt auf der Festplatte.", "gitSync.gitNotInstalled.title": "Git ist nicht installiert", "gitSync.gitNotInstalled.hint": "Git Sync benötigt das git-Programm im PATH. Installieren Sie git und laden Sie diese Seite neu.", "gitSync.mismatch.title": "Git-Bereich stimmt nicht überein", diff --git a/ui/src/i18n/locales/en.json b/ui/src/i18n/locales/en.json index 1845f5d0d..263539ea7 100644 --- a/ui/src/i18n/locales/en.json +++ b/ui/src/i18n/locales/en.json @@ -390,6 +390,11 @@ "gitSync.scope.initButton": "Initialize git repository", "gitSync.scope.initTitle": "Initialize git repository?", "gitSync.scope.initMessage": "Initialize a git repository at the \"{scope}\" scope and start version-controlling it from now on. The \"root\" scope versions skills, agents, and extras together.", + "gitSync.nested.title": "Root scope: action needed", + "gitSync.nested.hint": "These directories have their own .git and would upload as empty submodules — their files won't be tracked. Disabling renames .git to .git.disabled (reversible) so the files track normally.", + "gitSync.nested.disableButton": "Disable nested .git", + "gitSync.nested.disabled": "Disabled nested repo: {dirs}", + "gitSync.nested.configTracked": "config.yaml is tracked in this repo. It will be removed from version control automatically on the next commit or push; the file stays on disk.", "gitSync.gitNotInstalled.title": "Git is not installed", "gitSync.gitNotInstalled.hint": "Git Sync needs the git executable on your PATH. Install git and reload this page.", "gitSync.mismatch.title": "Git scope mismatch", diff --git a/ui/src/i18n/locales/es.json b/ui/src/i18n/locales/es.json index 5695692f8..70383b1ba 100644 --- a/ui/src/i18n/locales/es.json +++ b/ui/src/i18n/locales/es.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "Inicializar repositorio git", "gitSync.scope.initTitle": "¿Inicializar repositorio git?", "gitSync.scope.initMessage": "Inicializa un repositorio git en el ámbito \"{scope}\" y empieza a controlar sus versiones a partir de ahora. El ámbito \"root\" versiona skills, agents y extras juntos.", + "gitSync.nested.title": "Ámbito root: acción necesaria", + "gitSync.nested.hint": "Estos directorios tienen su propio .git y se subirían como submódulos vacíos: sus archivos no se rastrearán. Desactivar renombra .git a .git.disabled (reversible) para que los archivos se rastreen con normalidad.", + "gitSync.nested.disableButton": "Desactivar .git anidado", + "gitSync.nested.disabled": "Repositorio anidado desactivado: {dirs}", + "gitSync.nested.configTracked": "config.yaml está rastreado en este repositorio. Se eliminará del control de versiones automáticamente en el próximo commit o push; el archivo permanece en el disco.", "gitSync.gitNotInstalled.title": "Git no está instalado", "gitSync.gitNotInstalled.hint": "Git Sync necesita el ejecutable git en tu PATH. Instala git y vuelve a cargar esta página.", "gitSync.mismatch.title": "Discrepancia en el ámbito de git", diff --git a/ui/src/i18n/locales/fa.json b/ui/src/i18n/locales/fa.json index 891ef8fdb..a7e58ba99 100644 --- a/ui/src/i18n/locales/fa.json +++ b/ui/src/i18n/locales/fa.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "مقداردهی اولیه مخزن git", "gitSync.scope.initTitle": "مخزن git مقداردهی اولیه شود؟", "gitSync.scope.initMessage": "یک مخزن git در دامنه «{scope}» ایجاد می‌کند و از این پس آن را تحت کنترل نسخه قرار می‌دهد. دامنه «root» اسکیل‌ها، agentها و extras را با هم نسخه‌بندی می‌کند.", + "gitSync.nested.title": "محدودهٔ root: نیاز به اقدام", + "gitSync.nested.hint": "این پوشه‌ها .git مخصوص خود را دارند و هنگام آپلود به‌صورت زیرماژول خالی بارگذاری می‌شوند — فایل‌هایشان ردیابی نمی‌شوند. غیرفعال‌کردن، ‏.git را به ‎.git.disabled تغییر نام می‌دهد (برگشت‌پذیر) تا فایل‌ها به‌طور عادی ردیابی شوند.", + "gitSync.nested.disableButton": "غیرفعال‌کردن ‎.git تودرتو", + "gitSync.nested.disabled": "مخزن تودرتو غیرفعال شد: {dirs}", + "gitSync.nested.configTracked": "‏config.yaml در این مخزن ردیابی می‌شود. در commit یا push بعدی به‌طور خودکار از کنترل نسخه حذف می‌شود؛ فایل روی دیسک باقی می‌ماند.", "gitSync.gitNotInstalled.title": "Git نصب نشده است", "gitSync.gitNotInstalled.hint": "Git Sync به فایل اجرایی git در PATH شما نیاز دارد. git را نصب کنید و این صفحه را دوباره بارگذاری کنید.", "gitSync.mismatch.title": "ناهماهنگی محدوده git", diff --git a/ui/src/i18n/locales/fr.json b/ui/src/i18n/locales/fr.json index f368f3049..79ba8c4fe 100644 --- a/ui/src/i18n/locales/fr.json +++ b/ui/src/i18n/locales/fr.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "Initialiser le dépôt git", "gitSync.scope.initTitle": "Initialiser le dépôt git ?", "gitSync.scope.initMessage": "Initialise un dépôt git dans la portée « {scope} » et commence à en gérer les versions désormais. La portée « root » versionne skills, agents et extras ensemble.", + "gitSync.nested.title": "Portée root : action requise", + "gitSync.nested.hint": "Ces dossiers ont leur propre .git et seraient envoyés comme des sous-modules vides — leurs fichiers ne seront pas suivis. La désactivation renomme .git en .git.disabled (réversible) afin que les fichiers soient suivis normalement.", + "gitSync.nested.disableButton": "Désactiver le .git imbriqué", + "gitSync.nested.disabled": "Dépôt imbriqué désactivé : {dirs}", + "gitSync.nested.configTracked": "config.yaml est suivi dans ce dépôt. Il sera retiré du contrôle de version automatiquement au prochain commit ou push ; le fichier reste sur le disque.", "gitSync.gitNotInstalled.title": "Git n'est pas installé", "gitSync.gitNotInstalled.hint": "Git Sync nécessite l'exécutable git dans votre PATH. Installez git et rechargez cette page.", "gitSync.mismatch.title": "Incohérence de la portée git", diff --git a/ui/src/i18n/locales/id.json b/ui/src/i18n/locales/id.json index 42e6f45b3..35281bba8 100644 --- a/ui/src/i18n/locales/id.json +++ b/ui/src/i18n/locales/id.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "Inisialisasi repositori git", "gitSync.scope.initTitle": "Inisialisasi repositori git?", "gitSync.scope.initMessage": "Inisialisasi repositori git pada scope \"{scope}\" dan mulai mengontrol versinya mulai sekarang. Scope \"root\" memversikan skills, agents, dan extras sekaligus.", + "gitSync.nested.title": "Scope root: perlu tindakan", + "gitSync.nested.hint": "Direktori ini punya .git sendiri dan akan terunggah sebagai submodule kosong — file-nya tidak akan dilacak. Menonaktifkan akan mengganti nama .git menjadi .git.disabled (dapat dikembalikan) agar file-nya dilacak secara normal.", + "gitSync.nested.disableButton": "Nonaktifkan .git bersarang", + "gitSync.nested.disabled": "Repositori bersarang dinonaktifkan: {dirs}", + "gitSync.nested.configTracked": "config.yaml dilacak di repositori ini. Ini akan dihapus dari kontrol versi secara otomatis pada commit atau push berikutnya; file tetap ada di disk.", "gitSync.gitNotInstalled.title": "Git tidak terpasang", "gitSync.gitNotInstalled.hint": "Git Sync memerlukan executable git di PATH Anda. Pasang git lalu muat ulang halaman ini.", "gitSync.mismatch.title": "Cakupan git tidak cocok", diff --git a/ui/src/i18n/locales/ja.json b/ui/src/i18n/locales/ja.json index 2313d6734..6a6984eaf 100644 --- a/ui/src/i18n/locales/ja.json +++ b/ui/src/i18n/locales/ja.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "git リポジトリを初期化", "gitSync.scope.initTitle": "git リポジトリを初期化しますか?", "gitSync.scope.initMessage": "「{scope}」スコープに git リポジトリを初期化し、これ以降バージョン管理を開始します。「root」スコープは skills・agents・extras をまとめてバージョン管理します。", + "gitSync.nested.title": "Root スコープ: 対応が必要", + "gitSync.nested.hint": "これらのディレクトリは独自の .git を持ち、アップロードすると空のサブモジュールになります(ファイルは追跡されません)。無効化すると .git を .git.disabled にリネームし(元に戻せます)、ファイルが通常どおり追跡されます。", + "gitSync.nested.disableButton": "ネストした .git を無効化", + "gitSync.nested.disabled": "ネストしたリポジトリを無効化しました: {dirs}", + "gitSync.nested.configTracked": "config.yaml はこのリポジトリで追跡されています。次回の commit または push 時に自動的にバージョン管理から外されます(ファイルはディスクに残ります)。", "gitSync.gitNotInstalled.title": "Git がインストールされていません", "gitSync.gitNotInstalled.hint": "Git Sync には PATH 上に git 実行ファイルが必要です。git をインストールしてこのページを再読み込みしてください。", "gitSync.mismatch.title": "git スコープの不一致", diff --git a/ui/src/i18n/locales/ko.json b/ui/src/i18n/locales/ko.json index b9c969247..fd65f88f1 100644 --- a/ui/src/i18n/locales/ko.json +++ b/ui/src/i18n/locales/ko.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "git 저장소 초기화", "gitSync.scope.initTitle": "git 저장소를 초기화할까요?", "gitSync.scope.initMessage": "\"{scope}\" 스코프에 git 저장소를 초기화하고 지금부터 버전 관리를 시작합니다. \"root\" 스코프는 skills, agents, extras를 함께 버전 관리합니다.", + "gitSync.nested.title": "Root 스코프: 조치 필요", + "gitSync.nested.hint": "이 디렉터리들은 자체 .git을 가지고 있어 업로드 시 빈 서브모듈이 됩니다(파일이 추적되지 않음). 비활성화하면 .git을 .git.disabled로 이름을 바꿔(되돌릴 수 있음) 파일이 정상적으로 추적됩니다.", + "gitSync.nested.disableButton": "중첩된 .git 비활성화", + "gitSync.nested.disabled": "중첩 저장소를 비활성화함: {dirs}", + "gitSync.nested.configTracked": "config.yaml이 이 저장소에서 추적되고 있습니다. 다음 commit 또는 push 시 자동으로 버전 관리에서 제거됩니다(파일은 디스크에 남습니다).", "gitSync.gitNotInstalled.title": "Git가 설치되어 있지 않습니다", "gitSync.gitNotInstalled.hint": "Git Sync는 PATH에 git 실행 파일이 필요합니다. git을 설치한 후 이 페이지를 새로고침하세요.", "gitSync.mismatch.title": "git 범위 불일치", diff --git a/ui/src/i18n/locales/pt-BR.json b/ui/src/i18n/locales/pt-BR.json index a7a33c3a8..face181cd 100644 --- a/ui/src/i18n/locales/pt-BR.json +++ b/ui/src/i18n/locales/pt-BR.json @@ -564,6 +564,11 @@ "gitSync.scope.initButton": "Inicializar repositório git", "gitSync.scope.initTitle": "Inicializar repositório git?", "gitSync.scope.initMessage": "Inicializa um repositório git no escopo \"{scope}\" e passa a versioná-lo a partir de agora. O escopo \"root\" versiona skills, agents e extras juntos.", + "gitSync.nested.title": "Escopo root: ação necessária", + "gitSync.nested.hint": "Esses diretórios têm o próprio .git e seriam enviados como submódulos vazios — seus arquivos não serão versionados. Desativar renomeia .git para .git.disabled (reversível) para que os arquivos sejam versionados normalmente.", + "gitSync.nested.disableButton": "Desativar .git aninhado", + "gitSync.nested.disabled": "Repositório aninhado desativado: {dirs}", + "gitSync.nested.configTracked": "config.yaml está versionado neste repositório. Ele será removido do controle de versão automaticamente no próximo commit ou push; o arquivo permanece no disco.", "gitSync.gitNotInstalled.title": "Git não está instalado", "gitSync.gitNotInstalled.hint": "O Git Sync precisa do executável git no seu PATH. Instale o git e recarregue esta página.", "gitSync.mismatch.title": "Incompatibilidade de escopo do git", diff --git a/ui/src/i18n/locales/zh-CN.json b/ui/src/i18n/locales/zh-CN.json index 35f48dd7d..312670590 100644 --- a/ui/src/i18n/locales/zh-CN.json +++ b/ui/src/i18n/locales/zh-CN.json @@ -585,6 +585,11 @@ "gitSync.scope.initButton": "初始化 git 仓库", "gitSync.scope.initTitle": "初始化 git 仓库?", "gitSync.scope.initMessage": "在「{scope}」scope 初始化一个 git 仓库,并从现在开始对其进行版本控制。「root」scope 会把 skills、agents、extras 一起纳入版控。", + "gitSync.nested.title": "Root scope:需要处理", + "gitSync.nested.hint": "这些目录有自己的 .git,上传时会变成空的 submodule —— 里面的文件不会被追踪。停用会把 .git 改名为 .git.disabled(可逆),文件才能正常追踪。", + "gitSync.nested.disableButton": "停用 nested .git", + "gitSync.nested.disabled": "已停用 nested repo:{dirs}", + "gitSync.nested.configTracked": "config.yaml 当前被此 repo 追踪。下次 commit 或 push 时会自动移出版本控制;文件会保留在磁盘上。", "gitSync.gitNotInstalled.title": "未安装 Git", "gitSync.gitNotInstalled.hint": "Git Sync 需要 PATH 上有 git 可执行文件。请安装 git 后刷新此页。", "gitSync.mismatch.title": "Git 范围不一致", diff --git a/ui/src/i18n/locales/zh-TW.json b/ui/src/i18n/locales/zh-TW.json index 6129f2d15..cdf309f95 100644 --- a/ui/src/i18n/locales/zh-TW.json +++ b/ui/src/i18n/locales/zh-TW.json @@ -585,6 +585,11 @@ "gitSync.scope.initButton": "初始化 git 版本庫", "gitSync.scope.initTitle": "初始化 git 版本庫?", "gitSync.scope.initMessage": "在「{scope}」scope 初始化一個 git 版本庫,並從現在開始對它做版本控制。「root」scope 會把 skills、agents、extras 一起納入版控。", + "gitSync.nested.title": "Root scope:需要處理", + "gitSync.nested.hint": "這些目錄有自己的 .git,上傳時會變成空的 submodule —— 裡面的檔案不會被追蹤。停用會把 .git 改名為 .git.disabled(可逆),檔案才能正常追蹤。", + "gitSync.nested.disableButton": "停用 nested .git", + "gitSync.nested.disabled": "已停用 nested repo:{dirs}", + "gitSync.nested.configTracked": "config.yaml 目前被此 repo 追蹤。下次 commit 或 push 時會自動移出版本控制;檔案會保留在磁碟上。", "gitSync.gitNotInstalled.title": "未安裝 Git", "gitSync.gitNotInstalled.hint": "Git Sync 需要 PATH 上有 git 執行檔。請安裝 git 後重新整理此頁。", "gitSync.mismatch.title": "Git 範圍不一致", diff --git a/ui/src/pages/GitSyncPage.tsx b/ui/src/pages/GitSyncPage.tsx index 1d1594db3..dfcef61ef 100644 --- a/ui/src/pages/GitSyncPage.tsx +++ b/ui/src/pages/GitSyncPage.tsx @@ -136,6 +136,17 @@ export default function GitSyncPage() { }, }); + const absorbNestedMutation = useMutation({ + mutationFn: (subdirs: string[]) => api.gitAbsorbNested(subdirs), + onSuccess: (res) => { + toast(t('gitSync.nested.disabled', { dirs: res.disabled.join(', ') }), 'success'); + queryClient.invalidateQueries({ queryKey: queryKeys.gitStatus }); + }, + onError: (err: unknown) => { + toast(errorMessage(err), 'error'); + }, + }); + const [commitMsg, setCommitMsg] = useState(''); const [pushDryRun, setPushDryRun] = useState(false); const [pullDryRun, setPullDryRun] = useState(false); @@ -292,6 +303,42 @@ export default function GitSyncPage() { subtitle={t('gitSync.subtitle')} /> + {/* Root-scope hazards: nested submodule traps and a leaked config.yaml */} + {status?.isRepo && ((status.nestedRepos?.length ?? 0) > 0 || status.configTracked) && ( + +
+ + {t('gitSync.nested.title')} +
+ {(status.nestedRepos?.length ?? 0) > 0 && ( +
+

{t('gitSync.nested.hint')}

+
+ {status.nestedRepos.map((d) => ( + + {d} + + ))} +
+ +
+ )} + {status.configTracked && ( +

{t('gitSync.nested.configTracked')}

+ )} +
+ )} + {/* Repository Info Card — z-10 so branch dropdown renders above cards below */} {!status?.isRepo ? (