From e82b142e4ce2493289892074c1f069a8be7e753e Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 22:20:00 +0100 Subject: [PATCH 1/2] perf(trace): cut the CPU cost of the shell hook snapshots The pre and post hooks of every agent shell call took a snapshot of the checkout that hashed every file, for each checkout on the session record. - Read the ignore rules with go-git's gitignore.Scope as the walk goes down, so excluded folders such as node_modules and nested worktrees are never read. The deprecated ReadPatterns walked all of them. - Keep a hash cache per checkout. A file is read again only when its size, mtime, ctime or inode changed; files changed in the last two seconds are never cached. - Do not add a repository to the session when a shell command or a file tool works inside its .git folder. Closes #3858 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: dfa0c5da-5e77-4fac-bbb3-6be405e8b3a0 --- app/cli/internal/trace/git/exec.go | 7 - app/cli/internal/trace/git/git.go | 5 - app/cli/internal/trace/git/gogit.go | 108 --------- app/cli/internal/trace/git/gogit_test.go | 11 +- app/cli/internal/trace/git/snapshot.go | 211 ++++++++++++++++++ .../trace/git/snapshot_stat_darwin.go | 33 +++ .../internal/trace/git/snapshot_stat_linux.go | 33 +++ .../internal/trace/git/snapshot_stat_other.go | 26 +++ app/cli/internal/trace/git/snapshot_test.go | 209 +++++++++++++++++ app/cli/internal/trace/state/hashcache.go | 59 +++++ .../internal/trace/state/hashcache_test.go | 80 +++++++ app/cli/pkg/action/trace_agent_hook.go | 64 +++++- app/cli/pkg/action/trace_hook_handler_test.go | 3 - .../pkg/action/trace_shell_checkout_test.go | 58 +++++ 14 files changed, 766 insertions(+), 141 deletions(-) create mode 100644 app/cli/internal/trace/git/snapshot.go create mode 100644 app/cli/internal/trace/git/snapshot_stat_darwin.go create mode 100644 app/cli/internal/trace/git/snapshot_stat_linux.go create mode 100644 app/cli/internal/trace/git/snapshot_stat_other.go create mode 100644 app/cli/internal/trace/git/snapshot_test.go create mode 100644 app/cli/internal/trace/state/hashcache.go create mode 100644 app/cli/internal/trace/state/hashcache_test.go diff --git a/app/cli/internal/trace/git/exec.go b/app/cli/internal/trace/git/exec.go index 6bb864c44..54d8d5364 100644 --- a/app/cli/internal/trace/git/exec.go +++ b/app/cli/internal/trace/git/exec.go @@ -299,13 +299,6 @@ func (c *ExecClient) StagedFiles(repoRoot string) ([]string, error) { return strings.Split(strings.TrimRight(out, "\n"), "\n"), nil } -// SnapshotWorktree returns a signature of the working tree (repo-relative path -// → content hash). The walk is git-binary-independent, so it shares the -// implementation used by GoGitClient. -func (c *ExecClient) SnapshotWorktree(repoRoot string) (map[string]string, error) { - return snapshotWorktree(repoRoot) -} - // IsMergeCommit reports whether the commit at sha has more than one parent. func (c *ExecClient) IsMergeCommit(repoRoot, sha string) (bool, error) { cmd := exec.Command("git", "rev-list", "--no-walk", "--parents", sha) diff --git a/app/cli/internal/trace/git/git.go b/app/cli/internal/trace/git/git.go index ba857431f..395eb9456 100644 --- a/app/cli/internal/trace/git/git.go +++ b/app/cli/internal/trace/git/git.go @@ -129,11 +129,6 @@ type Client interface { GeneratedMatcher(repoRoot string) func(path string) bool // StagedFiles returns repo-relative paths of files staged for the current commit. StagedFiles(repoRoot string) ([]string, error) - // SnapshotWorktree returns a signature of the working tree as a map of - // repo-relative path (forward slashes) → content hash, skipping the .git - // directory and any .gitignore'd paths. Used to detect files changed by an - // agent-run shell command by diffing a before/after signature. - SnapshotWorktree(repoRoot string) (map[string]string, error) // SnapshotIndex returns staged regular-file paths and their blob hashes. SnapshotIndex(repoRoot string) (map[string]string, error) // IndexFile returns the staged content for a repo-relative path. diff --git a/app/cli/internal/trace/git/gogit.go b/app/cli/internal/trace/git/gogit.go index 2b0334fd1..ad8d884da 100644 --- a/app/cli/internal/trace/git/gogit.go +++ b/app/cli/internal/trace/git/gogit.go @@ -16,13 +16,7 @@ package git import ( - "crypto/sha256" - "encoding/hex" "fmt" - "io" - iofs "io/fs" - "os" - "path/filepath" "sort" "strings" "time" @@ -32,7 +26,6 @@ import ( gogit "github.com/go-git/go-git/v6" "github.com/go-git/go-git/v6/plumbing" "github.com/go-git/go-git/v6/plumbing/format/gitattributes" - "github.com/go-git/go-git/v6/plumbing/format/gitignore" "github.com/go-git/go-git/v6/plumbing/object" "github.com/go-git/go-git/v6/utils/merkletrie" ) @@ -295,107 +288,6 @@ func (c *GoGitClient) StagedFiles(repoRoot string) ([]string, error) { return files, nil } -// SnapshotWorktree returns a signature of the working tree (repo-relative path -// → SHA-256 content hash), honoring .gitignore and skipping the .git directory. -func (c *GoGitClient) SnapshotWorktree(repoRoot string) (map[string]string, error) { - return snapshotWorktree(repoRoot) -} - -// snapshotWorktree walks repoRoot and hashes every regular, non-ignored file. -// gitignore patterns are read in-process via go-git's parser (best-effort: an -// unreadable .gitignore yields no patterns rather than an error). Symlinks and -// unreadable files are skipped. The walk never fails the caller — attribution -// is best-effort and must not block the agent. -func snapshotWorktree(repoRoot string) (map[string]string, error) { - wtfs := osfs.New(repoRoot) - patterns, _ := gitignore.ReadPatterns(wtfs, nil) - matcher := gitignore.NewMatcher(patterns) - tracked := trackedPaths(repoRoot) - - sig := make(map[string]string) - err := filepath.WalkDir(repoRoot, func(p string, d iofs.DirEntry, err error) error { - if err != nil { - return nil // skip unreadable entries, keep walking - } - - rel, relErr := filepath.Rel(repoRoot, p) - if relErr != nil || rel == "." { - return nil - } - slashRel := filepath.ToSlash(rel) - parts := strings.Split(slashRel, "/") - - if d.IsDir() { - if d.Name() == ".git" || matcher.Match(parts, true) { - return filepath.SkipDir - } - - return nil - } - - if !d.Type().IsRegular() { - return nil - } - // Ignore rules apply only to untracked files, matching git: a tracked - // file that also matches a .gitignore pattern (e.g. force-added - // generated code) is still part of the working tree and must be - // snapshotted so edits to it are attributed. (Tracked files nested - // inside an ignored directory are the one gap — that directory is - // pruned above for walk performance.) - if matcher.Match(parts, false) && !tracked[slashRel] { - return nil - } - - h, herr := hashFileContent(p) - if herr != nil { - return nil - } - sig[slashRel] = h - - return nil - }) - - return sig, err -} - -// trackedPaths returns the set of repo-relative paths (forward-slash separated) -// recorded in the git index. Best-effort: returns nil when the repository or -// its index cannot be read, in which case ignore rules apply to every file. -func trackedPaths(repoRoot string) map[string]bool { - repo, err := openRepo(repoRoot) - if err != nil { - return nil - } - - idx, err := repo.Storer.Index() - if err != nil { - return nil - } - - tracked := make(map[string]bool, len(idx.Entries)) - for _, e := range idx.Entries { - tracked[e.Name] = true - } - - return tracked -} - -// hashFileContent returns the hex-encoded SHA-256 of the file's content. -func hashFileContent(path string) (string, error) { - f, err := os.Open(path) - if err != nil { - return "", err - } - defer func() { _ = f.Close() }() - - h := sha256.New() - if _, err := io.Copy(h, f); err != nil { - return "", err - } - - return hex.EncodeToString(h.Sum(nil)), nil -} - // IsMergeCommit reports whether the commit at sha has more than one parent. func (c *GoGitClient) IsMergeCommit(repoRoot, sha string) (bool, error) { repo, err := openRepo(repoRoot) diff --git a/app/cli/internal/trace/git/gogit_test.go b/app/cli/internal/trace/git/gogit_test.go index 2408be242..83d4b300b 100644 --- a/app/cli/internal/trace/git/gogit_test.go +++ b/app/cli/internal/trace/git/gogit_test.go @@ -472,7 +472,7 @@ func TestGoGitClient_Worktree(t *testing.T) { }) } -func TestGoGitClient_SnapshotWorktree(t *testing.T) { +func TestSnapshotWorktree(t *testing.T) { root := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(root, "keep.txt"), []byte("hello\n"), 0600)) require.NoError(t, os.MkdirAll(filepath.Join(root, "sub"), 0755)) @@ -485,8 +485,7 @@ func TestGoGitClient_SnapshotWorktree(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(root, ".git"), 0755)) require.NoError(t, os.WriteFile(filepath.Join(root, ".git", "config"), []byte("[core]\n"), 0600)) - c := NewGoGitClient() - sig, err := c.SnapshotWorktree(root) + sig, _, err := SnapshotWorktreeCached(root, nil) require.NoError(t, err) // Non-ignored files present (forward-slash keys), ignored + .git excluded. @@ -500,13 +499,13 @@ func TestGoGitClient_SnapshotWorktree(t *testing.T) { // Modifying a file changes its signature; adding one adds a key. require.NoError(t, os.WriteFile(filepath.Join(root, "keep.txt"), []byte("hello world\n"), 0600)) require.NoError(t, os.WriteFile(filepath.Join(root, "new.txt"), []byte("new\n"), 0600)) - sig2, err := c.SnapshotWorktree(root) + sig2, _, err := SnapshotWorktreeCached(root, nil) require.NoError(t, err) assert.NotEqual(t, sig["keep.txt"], sig2["keep.txt"]) assert.Contains(t, sig2, "new.txt") } -func TestGoGitClient_SnapshotWorktree_TrackedIgnoredFile(t *testing.T) { +func TestSnapshotWorktree_TrackedIgnoredFile(t *testing.T) { if _, err := exec.LookPath("git"); err != nil { t.Skip("git binary not found") } @@ -530,7 +529,7 @@ func TestGoGitClient_SnapshotWorktree_TrackedIgnoredFile(t *testing.T) { run("add", "normal.txt", ".gitignore") run("commit", "-m", "init") - sig, err := NewGoGitClient().SnapshotWorktree(root) + sig, _, err := SnapshotWorktreeCached(root, nil) require.NoError(t, err) assert.Contains(t, sig, "tracked.gen", "force-added tracked file must be snapshotted despite matching .gitignore") diff --git a/app/cli/internal/trace/git/snapshot.go b/app/cli/internal/trace/git/snapshot.go new file mode 100644 index 000000000..f1fbb3530 --- /dev/null +++ b/app/cli/internal/trace/git/snapshot.go @@ -0,0 +1,211 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package git + +import ( + "crypto/sha256" + "encoding/hex" + "io" + iofs "io/fs" + "os" + "path" + "path/filepath" + "strings" + "time" + + "github.com/go-git/go-billy/v6" + "github.com/go-git/go-billy/v6/osfs" + "github.com/go-git/go-git/v6/plumbing/format/gitignore" +) + +// racyWindow is how old the stat of a file must be before its hash is cached. +// A file can change again within the resolution of its timestamps (one second +// or more on some file systems) and keep the same stat. Its hash is read +// again until its stat is older than this, as git does with racily clean +// index entries. +const racyWindow = 2 * time.Second + +// CachedHash is the content hash of a file together with the stat of the file +// when it was hashed. While the stat stays the same, the content is taken to +// be the same. +type CachedHash struct { + Size int64 `json:"size"` + ModTime int64 `json:"mtime"` + // ChangeTime and Inode are zero on systems that do not report them. + // ChangeTime catches a change that keeps the size and resets the + // modification time, such as `touch -r`. + ChangeTime int64 `json:"ctime,omitempty"` + Inode uint64 `json:"ino,omitempty"` + Hash string `json:"hash"` +} + +// HashCache maps a repo-relative path (forward slashes) to the cached hash of +// the file. +type HashCache map[string]CachedHash + +// SnapshotWorktreeCached returns a signature of the working tree +// (repo-relative path → SHA-256 content hash), honoring .gitignore and +// skipping the .git directory. A file whose stat matches its entry in cache is +// not read: its hash comes from the cache. It also returns the cache for the +// next snapshot, with the files that this snapshot saw. A nil cache hashes +// every file. +func SnapshotWorktreeCached(repoRoot string, cache HashCache) (map[string]string, HashCache, error) { + return snapshotWorktree(osfs.New(repoRoot), repoRoot, cache, time.Now().Add(-racyWindow)) +} + +// snapshotWorktree walks repoRoot and hashes every regular file that is not +// ignored. The ignore rules are read from wtfs, the file system of repoRoot. A +// file with a stat older than cutoff goes into the returned cache. Symlinks +// and files that cannot be read are skipped. The walk never fails the caller: +// attribution is best-effort and must not block the agent. +func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, cutoff time.Time) (map[string]string, HashCache, error) { + // The ignore rules are read as the walk goes down, one folder at a time, + // so a folder that a rule excludes is never read (best-effort: a rules + // file that cannot be read gives no rules rather than an error). + rootPatterns, _ := gitignore.RootPatterns(wtfs) + scopes := map[string]*gitignore.Scope{".": gitignore.NewScope(rootPatterns)} + tracked := trackedPaths(repoRoot) + cutoffNano := cutoff.UnixNano() + + hashes := make(map[string]string) + next := make(HashCache) + err := filepath.WalkDir(repoRoot, func(p string, d iofs.DirEntry, err error) error { + if err != nil { + return nil // skip unreadable entries, keep walking + } + + rel, relErr := filepath.Rel(repoRoot, p) + if relErr != nil || rel == "." { + return nil + } + slashRel := filepath.ToSlash(rel) + parts := strings.Split(slashRel, "/") + // The walk visits a folder before its entries, so the scope of the + // parent is always there. + scope := scopes[path.Dir(slashRel)] + + if d.IsDir() { + if d.Name() == ".git" { + return filepath.SkipDir + } + // When the rules of this folder cannot be read, the inherited + // ones still apply. + child, _ := scope.Descend(parts, func() ([]gitignore.Pattern, error) { + own, _ := gitignore.DirPatterns(wtfs, parts) + return own, nil + }) + if child.Excluded() { + return filepath.SkipDir + } + scopes[slashRel] = child + + return nil + } + + if !d.Type().IsRegular() { + return nil + } + // Ignore rules apply only to untracked files, matching git: a tracked + // file that also matches a .gitignore pattern (e.g. force-added + // generated code) is still part of the working tree and must be + // snapshotted so edits to it are attributed. (Tracked files nested + // inside an ignored directory are the one gap: git does not read + // below an excluded directory, and neither does the walk.) + if scope.Match(parts, false) && !tracked[slashRel] { + return nil + } + + // The stat is taken before the content is read. A change after it + // gives a new stat, so a stale hash is never cached under a current + // stat. + info, err := d.Info() + if err != nil { + return nil + } + entry := statEntry(info) + + if cached, ok := cache[slashRel]; ok && cached.sameStat(entry) { + entry.Hash = cached.Hash + } else { + h, err := hashFileContent(p) + if err != nil { + return nil + } + entry.Hash = h + } + + hashes[slashRel] = entry.Hash + if entry.ModTime < cutoffNano && entry.ChangeTime < cutoffNano { + next[slashRel] = entry + } + + return nil + }) + + return hashes, next, err +} + +// statEntry returns the stat part of a cache entry for a file. +func statEntry(info iofs.FileInfo) CachedHash { + entry := CachedHash{Size: info.Size(), ModTime: info.ModTime().UnixNano()} + entry.ChangeTime, entry.Inode = changeTimeAndInode(info) + + return entry +} + +// sameStat reports whether c and other have the same stat. +func (c CachedHash) sameStat(other CachedHash) bool { + return c.Size == other.Size && c.ModTime == other.ModTime && + c.ChangeTime == other.ChangeTime && c.Inode == other.Inode +} + +// trackedPaths returns the set of repo-relative paths (forward-slash separated) +// recorded in the git index. Best-effort: returns nil when the repository or +// its index cannot be read, in which case ignore rules apply to every file. +func trackedPaths(repoRoot string) map[string]bool { + repo, err := openRepo(repoRoot) + if err != nil { + return nil + } + + idx, err := repo.Storer.Index() + if err != nil { + return nil + } + + tracked := make(map[string]bool, len(idx.Entries)) + for _, e := range idx.Entries { + tracked[e.Name] = true + } + + return tracked +} + +// hashFileContent returns the hex-encoded SHA-256 of the file's content. +func hashFileContent(name string) (string, error) { + f, err := os.Open(name) + if err != nil { + return "", err + } + defer func() { _ = f.Close() }() + + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return "", err + } + + return hex.EncodeToString(h.Sum(nil)), nil +} diff --git a/app/cli/internal/trace/git/snapshot_stat_darwin.go b/app/cli/internal/trace/git/snapshot_stat_darwin.go new file mode 100644 index 000000000..8d7e26bac --- /dev/null +++ b/app/cli/internal/trace/git/snapshot_stat_darwin.go @@ -0,0 +1,33 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package git + +import ( + iofs "io/fs" + "syscall" +) + +// changeTimeAndInode returns the status change time (nanoseconds) and the +// inode of a file, or zeros when the stat does not hold them. +func changeTimeAndInode(info iofs.FileInfo) (int64, uint64) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, 0 + } + sec, nsec := st.Ctimespec.Unix() + + return sec*1e9 + nsec, st.Ino +} diff --git a/app/cli/internal/trace/git/snapshot_stat_linux.go b/app/cli/internal/trace/git/snapshot_stat_linux.go new file mode 100644 index 000000000..113c17323 --- /dev/null +++ b/app/cli/internal/trace/git/snapshot_stat_linux.go @@ -0,0 +1,33 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package git + +import ( + iofs "io/fs" + "syscall" +) + +// changeTimeAndInode returns the status change time (nanoseconds) and the +// inode of a file, or zeros when the stat does not hold them. +func changeTimeAndInode(info iofs.FileInfo) (int64, uint64) { + st, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, 0 + } + sec, nsec := st.Ctim.Unix() + + return sec*1e9 + nsec, st.Ino +} diff --git a/app/cli/internal/trace/git/snapshot_stat_other.go b/app/cli/internal/trace/git/snapshot_stat_other.go new file mode 100644 index 000000000..1f3e7c3b4 --- /dev/null +++ b/app/cli/internal/trace/git/snapshot_stat_other.go @@ -0,0 +1,26 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !linux && !darwin + +package git + +import iofs "io/fs" + +// changeTimeAndInode returns zeros: this system does not report them in a +// portable way, so the cache compares the size and modification time only. +func changeTimeAndInode(iofs.FileInfo) (int64, uint64) { + return 0, 0 +} diff --git a/app/cli/internal/trace/git/snapshot_test.go b/app/cli/internal/trace/git/snapshot_test.go new file mode 100644 index 000000000..b073490e6 --- /dev/null +++ b/app/cli/internal/trace/git/snapshot_test.go @@ -0,0 +1,209 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package git + +import ( + iofs "io/fs" + "os" + "path/filepath" + "testing" + "time" + + "github.com/go-git/go-billy/v6" + "github.com/go-git/go-billy/v6/osfs" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func writeTestFile(t *testing.T, root, rel, content string) { + t.Helper() + p := filepath.Join(root, filepath.FromSlash(rel)) + require.NoError(t, os.MkdirAll(filepath.Dir(p), 0755)) + require.NoError(t, os.WriteFile(p, []byte(content), 0600)) +} + +// snapshot takes a snapshot of root with the given cache and cutoff. +func snapshot(t *testing.T, root string, cache HashCache, cutoff time.Time) (map[string]string, HashCache) { + t.Helper() + hashes, next, err := snapshotWorktree(osfs.New(root), root, cache, cutoff) + require.NoError(t, err) + + return hashes, next +} + +// recordingFS records each path that the ignore rules are read from. +type recordingFS struct { + billy.Filesystem + paths []string +} + +func (r *recordingFS) Open(name string) (billy.File, error) { + r.paths = append(r.paths, filepath.ToSlash(name)) + return r.Filesystem.Open(name) +} + +func (r *recordingFS) ReadDir(name string) ([]iofs.DirEntry, error) { + r.paths = append(r.paths, filepath.ToSlash(name)) + return r.Filesystem.ReadDir(name) +} + +// A folder that an ancestor's .gitignore excludes is never read: git does +// not read below an excluded folder, and nothing there can change what the +// snapshot holds. Reading it anyway made the snapshot of a checkout with +// node_modules or nested worktrees in it many times slower. +func TestSnapshotWorktree_DoesNotReadBelowExcludedFolders(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, ".gitignore", "**/node_modules/\n") + writeTestFile(t, root, "a/node_modules/pkg/.gitignore", "!*\n") + writeTestFile(t, root, "a/node_modules/pkg/index.js", "module.exports = 1\n") + writeTestFile(t, root, "a/main.go", "package a\n") + writeTestFile(t, root, "zz/.gitignore", "*.log\n") + writeTestFile(t, root, "zz/build.log", "log\n") + writeTestFile(t, root, "zz/main.go", "package zz\n") + + rec := &recordingFS{Filesystem: osfs.New(root)} + hashes, _, err := snapshotWorktree(rec, root, nil, time.Now()) + require.NoError(t, err) + + assert.Contains(t, hashes, "a/main.go") + assert.Contains(t, hashes, "zz/main.go") + assert.NotContains(t, hashes, "zz/build.log", "the rules of a nested .gitignore apply") + assert.NotContains(t, hashes, "a/node_modules/pkg/index.js", "a rule below an excluded folder cannot include a file again") + + require.NotEmpty(t, rec.paths, "the ignore rules are read through the given file system") + for _, p := range rec.paths { + assert.NotContains(t, p, "node_modules", "nothing below an excluded folder is read") + } +} + +// Rules of a nested .gitignore apply to its own folder only. +func TestSnapshotWorktree_NestedRulesAreScoped(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "sub/.gitignore", "*.tmp\n") + writeTestFile(t, root, "sub/x.tmp", "tmp\n") + writeTestFile(t, root, "other/x.tmp", "tmp\n") + + hashes, _ := snapshot(t, root, nil, time.Now()) + + assert.NotContains(t, hashes, "sub/x.tmp") + assert.Contains(t, hashes, "other/x.tmp") +} + +func TestSnapshotWorktreeCached(t *testing.T) { + const sentinel = "hash-from-the-cache" + // A cutoff in the future lets the snapshot cache every file. The racy + // case sets one in the past. + future := time.Now().Add(time.Hour) + + testCases := []struct { + name string + // change runs between the snapshot that fills the cache and the one + // that reads it. + change func(t *testing.T, root string) + // wantSentinel is whether the second snapshot takes the hash of + // a.txt from the cache. + wantSentinel bool + wantMissing bool + }{ + { + name: "a file with the same stat takes its hash from the cache", + change: func(*testing.T, string) {}, + wantSentinel: true, + }, + { + name: "a file with a new size is hashed again", + change: func(t *testing.T, root string) { + writeTestFile(t, root, "a.txt", "a longer content\n") + }, + }, + { + name: "a file with the same size and a new modification time is hashed again", + change: func(t *testing.T, root string) { + writeTestFile(t, root, "a.txt", "b\n") + later := time.Now().Add(time.Minute) + require.NoError(t, os.Chtimes(filepath.Join(root, "a.txt"), later, later)) + }, + }, + { + name: "a deleted file is not in the snapshot", + change: func(t *testing.T, root string) { + require.NoError(t, os.Remove(filepath.Join(root, "a.txt"))) + }, + wantMissing: true, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "a.txt", "a\n") + writeTestFile(t, root, "b.txt", "b\n") + + _, cache := snapshot(t, root, nil, future) + require.Contains(t, cache, "a.txt") + entry := cache["a.txt"] + entry.Hash = sentinel + cache["a.txt"] = entry + + tc.change(t, root) + + hashes, next := snapshot(t, root, cache, future) + uncached, _ := snapshot(t, root, nil, future) + + switch { + case tc.wantMissing: + assert.NotContains(t, hashes, "a.txt") + assert.NotContains(t, next, "a.txt", "a deleted file leaves the cache") + case tc.wantSentinel: + assert.Equal(t, sentinel, hashes["a.txt"]) + default: + assert.Equal(t, uncached["a.txt"], hashes["a.txt"]) + assert.Equal(t, uncached["a.txt"], next["a.txt"].Hash) + } + assert.Equal(t, uncached["b.txt"], hashes["b.txt"]) + }) + } +} + +// A file whose stat is not older than the cutoff can still change within the +// resolution of its timestamps without a change of its stat. Its hash is not +// cached, so the next snapshot reads it again. +func TestSnapshotWorktreeCached_DoesNotCacheRecentFiles(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "a.txt", "a\n") + + hashes, cache := snapshot(t, root, nil, time.Now().Add(-time.Hour)) + + assert.Contains(t, hashes, "a.txt") + assert.NotContains(t, cache, "a.txt") +} + +// A snapshot that takes its hashes from the cache holds what a snapshot +// without a cache holds. +func TestSnapshotWorktreeCached_MatchesUncachedSnapshot(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, ".gitignore", "ignored.txt\nbuild/\n") + writeTestFile(t, root, "keep.txt", "hello\n") + writeTestFile(t, root, "ignored.txt", "secret\n") + writeTestFile(t, root, "build/out.bin", "artifact\n") + writeTestFile(t, root, "sub/nested.go", "package sub\n") + + uncached, cache := snapshot(t, root, nil, time.Now().Add(time.Hour)) + require.Len(t, cache, len(uncached), "every file is cached") + + cached, _ := snapshot(t, root, cache, time.Now().Add(time.Hour)) + assert.Equal(t, uncached, cached) +} diff --git a/app/cli/internal/trace/state/hashcache.go b/app/cli/internal/trace/state/hashcache.go new file mode 100644 index 000000000..8ad5ec671 --- /dev/null +++ b/app/cli/internal/trace/state/hashcache.go @@ -0,0 +1,59 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package state + +import ( + "encoding/json" + "os" + "path/filepath" + + tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git" +) + +// worktreeHashCacheFile holds the content hashes of the files of the +// checkout, with the stat of each file when it was hashed. It is a cache for +// the snapshots that the shell hooks take of the working tree, shared by every +// session of the checkout. It is not single-use push data, so WipeTraceDir +// keeps it. +const worktreeHashCacheFile = "worktree-hashes.json" + +func (s *Store) worktreeHashCachePath() string { + return filepath.Join(s.traceDirPath(), worktreeHashCacheFile) +} + +// LoadWorktreeHashCache returns the cached file hashes of the checkout. A +// cache that is missing or does not parse gives nil: the next snapshot then +// hashes every file. +func (s *Store) LoadWorktreeHashCache() tracegit.HashCache { + data, err := os.ReadFile(s.worktreeHashCachePath()) + if err != nil { + return nil + } + + var cache tracegit.HashCache + if err := json.Unmarshal(data, &cache); err != nil { + return nil + } + + return cache +} + +// SaveWorktreeHashCache replaces the cached file hashes of the checkout. The +// write is atomic, so hooks that run at the same time read a whole cache: the +// last write wins, and a lost one only costs a hash again. +func (s *Store) SaveWorktreeHashCache(cache tracegit.HashCache) error { + return writeJSONAtomic(s.worktreeHashCachePath(), cache) +} diff --git a/app/cli/internal/trace/state/hashcache_test.go b/app/cli/internal/trace/state/hashcache_test.go new file mode 100644 index 000000000..91a92b936 --- /dev/null +++ b/app/cli/internal/trace/state/hashcache_test.go @@ -0,0 +1,80 @@ +// +// Copyright 2026 The Chainloop Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package state + +import ( + "os" + "testing" + + tracegit "github.com/chainloop-dev/chainloop/app/cli/internal/trace/git" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestWorktreeHashCache(t *testing.T) { + cache := tracegit.HashCache{ + "a.txt": {Size: 2, ModTime: 10, ChangeTime: 11, Inode: 12, Hash: "h1"}, + "sub/b.txt": {Size: 3, ModTime: 20, Hash: "h2"}, + } + + testCases := []struct { + name string + setup func(t *testing.T, store *Store) + want tracegit.HashCache + }{ + { + name: "a store without a cache gives an empty one", + want: nil, + }, + { + name: "a saved cache loads back", + setup: func(t *testing.T, store *Store) { + require.NoError(t, store.SaveWorktreeHashCache(cache)) + }, + want: cache, + }, + { + name: "a cache that does not parse is ignored", + setup: func(t *testing.T, store *Store) { + require.NoError(t, os.MkdirAll(store.traceDirPath(), 0o755)) + require.NoError(t, os.WriteFile(store.worktreeHashCachePath(), []byte("{not json"), 0o600)) + }, + want: nil, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + store := NewGitStore(t.TempDir()) + if tc.setup != nil { + tc.setup(t, store) + } + + assert.Equal(t, tc.want, store.LoadWorktreeHashCache()) + }) + } +} + +// The cache is not single-use data of one push: a push keeps it. +func TestWorktreeHashCache_SurvivesWipe(t *testing.T) { + store := NewGitStore(t.TempDir()) + cache := tracegit.HashCache{"a.txt": {Size: 1, Hash: "h"}} + require.NoError(t, store.SaveWorktreeHashCache(cache)) + + require.NoError(t, store.WipeTraceDir()) + + assert.Equal(t, cache, store.LoadWorktreeHashCache()) +} diff --git a/app/cli/pkg/action/trace_agent_hook.go b/app/cli/pkg/action/trace_agent_hook.go index 30d051c2b..c2dfdaeeb 100644 --- a/app/cli/pkg/action/trace_agent_hook.go +++ b/app/cli/pkg/action/trace_agent_hook.go @@ -19,6 +19,7 @@ import ( "context" "errors" "fmt" + "maps" "os" "path/filepath" "slices" @@ -448,16 +449,6 @@ func shellCallKey(input *trace.HookInput) state.ShellCallKey { func captureWorktreeSnapshot(store *state.Store, repoRoot string, key state.ShellCallKey, log zerolog.Logger) { client := tracegit.NewGitClient() for _, root := range shellSnapshotRoots(store, repoRoot, key.SessionID) { - worktreeSig, err := client.SnapshotWorktree(root) - if err != nil { - log.Debug().Err(err).Str("root", root).Msg("pre-command: worktree snapshot failed") - continue - } - indexSig, err := client.SnapshotIndex(root) - if err != nil { - log.Debug().Err(err).Str("root", root).Msg("pre-command: index snapshot failed") - } - rootStore := store if !sameDir(root, repoRoot) { s, resolvedRoot, err := state.LocateFrom(root) @@ -471,6 +462,16 @@ func captureWorktreeSnapshot(store *state.Store, repoRoot string, key state.Shel } } + worktreeSig, err := snapshotCheckout(rootStore, root, log) + if err != nil { + log.Debug().Err(err).Str("root", root).Msg("pre-command: worktree snapshot failed") + continue + } + indexSig, err := client.SnapshotIndex(root) + if err != nil { + log.Debug().Err(err).Str("root", root).Msg("pre-command: index snapshot failed") + } + heads := make(map[string]string) // A checkout with no commit yet has no HEAD; its files count as new. // It is saved with an empty HEAD, so that the post hook can tell it @@ -503,6 +504,27 @@ func captureWorktreeSnapshot(store *state.Store, repoRoot string, key state.Shel } } +// snapshotCheckout returns the working-tree signature of a checkout. Files +// whose stat did not change since an earlier snapshot of the checkout take +// their hash from the cache in store, so the pre and post hooks of a shell +// command read only the files that changed. The cache is saved for the next +// snapshot when it changed. +func snapshotCheckout(store *state.Store, root string, log zerolog.Logger) (map[string]string, error) { + cache := store.LoadWorktreeHashCache() + sig, next, err := tracegit.SnapshotWorktreeCached(root, cache) + if err != nil { + return nil, err + } + + if !maps.Equal(cache, next) { + if err := store.SaveWorktreeHashCache(next); err != nil { + log.Debug().Err(err).Str("root", root).Msg("save worktree hash cache failed") + } + } + + return sig, nil +} + func copySessionRecord(source, target *state.Store, sessionID string) error { rec, err := source.LoadSessionRecord(sessionID) if err != nil { @@ -595,7 +617,12 @@ func registerCommandCheckouts(provider trace.Provider, input *trace.HookInput, h for _, dir := range commandCheckoutDirs(input.Command, cwd) { // A directory that does not exist yet (the target of a clone, at the - // pre hook) must not resolve to a repository above it. + // pre hook) must not resolve to a repository above it. A directory + // inside a .git folder resolves to the repository of that folder, + // but a command there does not work in its checkout. + if insideGitDir(dir) { + continue + } if _, err := os.Stat(dir); err != nil { continue } @@ -611,6 +638,13 @@ func registerCommandCheckouts(provider trace.Provider, input *trace.HookInput, h } } +// insideGitDir reports whether dir is a .git folder or a folder below one. A +// path there resolves to the repository of that folder, but a tool that works +// there does not work in its checkout. +func insideGitDir(dir string) bool { + return slices.Contains(strings.Split(filepath.ToSlash(filepath.Clean(dir)), "/"), ".git") +} + // sameDir reports whether a and b name the same directory, ignoring symlinks // (e.g. /var and /private/var on macOS). func sameDir(a, b string) bool { @@ -736,6 +770,12 @@ func recordTranscriptPath(store *state.Store, rec *state.SessionRecord, transcri // session there. func locateForHook(provider trace.Provider, input *trace.HookInput) (*state.Store, string, error) { if input.FilePath != "" && provider.IsFileWritingTool(input.ToolName) { + // A file inside a .git folder (info/exclude, a hook) is not a file + // of the checkout, and its repository must not join the session. + if insideGitDir(filepath.Dir(input.FilePath)) { + return nil, "", fmt.Errorf("%s is inside a .git folder, not in a checkout", input.FilePath) + } + return state.LocateFrom(filepath.Dir(input.FilePath)) } @@ -1011,7 +1051,7 @@ type preCommand struct { // untracked file counts as new. func recordRootChanges(store *state.Store, repoRoot string, pre preCommand, before map[string]string, sessionID string, log zerolog.Logger) { client := tracegit.NewGitClient() - after, err := client.SnapshotWorktree(repoRoot) + after, err := snapshotCheckout(store, repoRoot, log) if err != nil { log.Debug().Err(err).Str("root", repoRoot).Msg("post-command: worktree snapshot failed") return diff --git a/app/cli/pkg/action/trace_hook_handler_test.go b/app/cli/pkg/action/trace_hook_handler_test.go index 58b953e4b..0e8729f0d 100644 --- a/app/cli/pkg/action/trace_hook_handler_test.go +++ b/app/cli/pkg/action/trace_hook_handler_test.go @@ -319,9 +319,6 @@ func (f *fakeBranchClient) GeneratedMatcher(string) func(string) bool { return func(string) bool { return false } } func (f *fakeBranchClient) StagedFiles(string) ([]string, error) { return nil, nil } -func (f *fakeBranchClient) SnapshotWorktree(string) (map[string]string, error) { - return nil, nil -} func (f *fakeBranchClient) SnapshotIndex(string) (map[string]string, error) { return nil, nil } diff --git a/app/cli/pkg/action/trace_shell_checkout_test.go b/app/cli/pkg/action/trace_shell_checkout_test.go index 76fec4873..f3abf7a4f 100644 --- a/app/cli/pkg/action/trace_shell_checkout_test.go +++ b/app/cli/pkg/action/trace_shell_checkout_test.go @@ -223,6 +223,64 @@ func TestShellCommandInOtherCheckout(t *testing.T) { } } +// A command that works inside the .git folder of a repository, such as +// `cd /.git/worktrees/` to read the state of a linked worktree, +// does not work in its checkout. The repository is not added to the session: +// each checkout on the session is snapshotted on every later shell call. +func TestShellCommandInsideGitFolderIsNotACheckout(t *testing.T) { + const sid = "ses_3858" + p := opencode.New() + + mainRoot := chdirToResolvedGitRepo(t) + other := resolvedTempGitRepo(t) + otherGitDir := filepath.Join(other, ".git") + require.NoError(t, os.MkdirAll(filepath.Join(otherGitDir, "worktrees", "wt"), 0o755)) + + withStdin(t, fmt.Sprintf(`{"session_id":%q,"hook_event_name":"session.created"}`, sid)) + captureStdout(t, func() { require.NoError(t, HandleAgentSessionStart(p, nil, zerolog.Nop())) }) + + for _, command := range []string{ + fmt.Sprintf("cd %s && ls", filepath.Join(otherGitDir, "worktrees", "wt")), + fmt.Sprintf("cd %s && cat HEAD", otherGitDir), + } { + pre := fmt.Sprintf(`{"session_id":%q,"hook_event_name":"tool.execute.before","tool_name":"bash","tool_use_id":"call_01","command":%q}`, sid, command) + post := fmt.Sprintf(`{"session_id":%q,"hook_event_name":"tool.execute.after","tool_name":"bash","tool_use_id":"call_01","command":%q}`, sid, command) + + withStdin(t, pre) + captureStdout(t, func() { require.NoError(t, HandleAgentPreToolUse(p, zerolog.Nop())) }) + withStdin(t, post) + captureStdout(t, func() { require.NoError(t, HandleAgentPostToolUse(p, zerolog.Nop())) }) + } + + rec, err := state.NewGitStore(filepath.Join(mainRoot, ".git")).LoadSessionRecord(sid) + require.NoError(t, err) + require.NotNil(t, rec) + assert.Empty(t, rec.Checkouts, "a folder inside .git is not a checkout") + assert.False(t, state.NewGitStore(otherGitDir).SessionRecordExists(sid), "the session is not tracked in the other repository") +} + +// A file tool that writes a file inside the .git folder of a repository, such +// as .git/info/exclude, does not edit its checkout: no trace state is located +// for it, so the repository is not added to the session. +func TestLocateForHook_FileInsideGitFolder(t *testing.T) { + chdirToResolvedGitRepo(t) + other := resolvedTempGitRepo(t) + + for _, file := range []string{ + filepath.Join(other, ".git", "info", "exclude"), + filepath.Join(other, ".git", "worktrees", "wt", "HEAD"), + } { + input := &trace.HookInput{SessionID: "ses_3858", ToolName: "Write", FilePath: file} + _, _, err := locateForHook(claude.New(), input) + assert.Error(t, err, file) + } + + input := &trace.HookInput{SessionID: "ses_3858", ToolName: "Write", FilePath: filepath.Join(other, "notes.md")} + _, root, err := locateForHook(claude.New(), input) + require.NoError(t, err) + assert.Equal(t, other, root, "a file of the checkout still resolves to it") +} + func configureGitUser(t *testing.T, dir string) { t.Helper() runGit(t, dir, "config", "user.email", "test@test.com") From 11aefc9583e99571841b0658a648f87081d894ee Mon Sep 17 00:00:00 2001 From: Miguel Martinez Trivino Date: Mon, 30 Nov 2026 22:33:46 +0100 Subject: [PATCH 2/2] fix(trace): address review of the shell hook snapshot changes - Snapshot the tracked files below an excluded folder, as git status does, so shell edits of a committed file in a folder that a later .gitignore rule excludes are attributed. The folder is walked only when the index tracks files below it, and no ignore rules are read there. - Do not read a cached hash for a file with a recent stat, as well as not writing one. - Check the path of a file tool write itself for .git, so a write to the .git file of a linked worktree does not join its repository to the session. Refs #3858 Assisted-by: Claude Code Signed-off-by: Miguel Martinez Trivino Chainloop-Trace-Sessions: dfa0c5da-5e77-4fac-bbb3-6be405e8b3a0 --- app/cli/internal/trace/git/snapshot.go | 30 ++++++++-- app/cli/internal/trace/git/snapshot_test.go | 60 +++++++++++++++++++ app/cli/pkg/action/trace_agent_hook.go | 18 +++--- .../pkg/action/trace_shell_checkout_test.go | 2 + 4 files changed, 96 insertions(+), 14 deletions(-) diff --git a/app/cli/internal/trace/git/snapshot.go b/app/cli/internal/trace/git/snapshot.go index f1fbb3530..fda1b41ba 100644 --- a/app/cli/internal/trace/git/snapshot.go +++ b/app/cli/internal/trace/git/snapshot.go @@ -78,6 +78,7 @@ func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, c rootPatterns, _ := gitignore.RootPatterns(wtfs) scopes := map[string]*gitignore.Scope{".": gitignore.NewScope(rootPatterns)} tracked := trackedPaths(repoRoot) + trackedDirs := parentDirs(tracked) cutoffNano := cutoff.UnixNano() hashes := make(map[string]string) @@ -107,7 +108,9 @@ func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, c own, _ := gitignore.DirPatterns(wtfs, parts) return own, nil }) - if child.Excluded() { + // An excluded folder is walked only for the tracked files below + // it. No ignore rules are read there: its scope stays excluded. + if child.Excluded() && !trackedDirs[slashRel] { return filepath.SkipDir } scopes[slashRel] = child @@ -121,9 +124,8 @@ func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, c // Ignore rules apply only to untracked files, matching git: a tracked // file that also matches a .gitignore pattern (e.g. force-added // generated code) is still part of the working tree and must be - // snapshotted so edits to it are attributed. (Tracked files nested - // inside an ignored directory are the one gap: git does not read - // below an excluded directory, and neither does the walk.) + // snapshotted so edits to it are attributed, also below an ignored + // directory. if scope.Match(parts, false) && !tracked[slashRel] { return nil } @@ -137,7 +139,10 @@ func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, c } entry := statEntry(info) - if cached, ok := cache[slashRel]; ok && cached.sameStat(entry) { + // A file with a recent stat can change again without a change of its + // stat, so its cached hash is neither read nor written. + settled := entry.ModTime < cutoffNano && entry.ChangeTime < cutoffNano + if cached, ok := cache[slashRel]; ok && settled && cached.sameStat(entry) { entry.Hash = cached.Hash } else { h, err := hashFileContent(p) @@ -148,7 +153,7 @@ func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, c } hashes[slashRel] = entry.Hash - if entry.ModTime < cutoffNano && entry.ChangeTime < cutoffNano { + if settled { next[slashRel] = entry } @@ -158,6 +163,19 @@ func snapshotWorktree(wtfs billy.Filesystem, repoRoot string, cache HashCache, c return hashes, next, err } +// parentDirs returns every folder (forward slashes) that holds one of paths, +// directly or below. +func parentDirs(paths map[string]bool) map[string]bool { + dirs := make(map[string]bool) + for p := range paths { + for dir := path.Dir(p); dir != "." && !dirs[dir]; dir = path.Dir(dir) { + dirs[dir] = true + } + } + + return dirs +} + // statEntry returns the stat part of a cache entry for a file. func statEntry(info iofs.FileInfo) CachedHash { entry := CachedHash{Size: info.Size(), ModTime: info.ModTime().UnixNano()} diff --git a/app/cli/internal/trace/git/snapshot_test.go b/app/cli/internal/trace/git/snapshot_test.go index b073490e6..49afa97b9 100644 --- a/app/cli/internal/trace/git/snapshot_test.go +++ b/app/cli/internal/trace/git/snapshot_test.go @@ -18,6 +18,7 @@ package git import ( iofs "io/fs" "os" + "os/exec" "path/filepath" "testing" "time" @@ -191,6 +192,65 @@ func TestSnapshotWorktreeCached_DoesNotCacheRecentFiles(t *testing.T) { assert.NotContains(t, cache, "a.txt") } +// A cache entry whose stat is not older than the cutoff is not trusted, even +// when the stat matches: the file can have changed within the resolution of +// its timestamps. +func TestSnapshotWorktreeCached_DoesNotReadRecentEntries(t *testing.T) { + root := t.TempDir() + writeTestFile(t, root, "a.txt", "a\n") + + _, cache := snapshot(t, root, nil, time.Now().Add(time.Hour)) + require.Contains(t, cache, "a.txt") + entry := cache["a.txt"] + entry.Hash = "hash-from-the-cache" + cache["a.txt"] = entry + + hashes, _ := snapshot(t, root, cache, time.Now().Add(-time.Hour)) + uncached, _ := snapshot(t, root, nil, time.Now()) + + assert.Equal(t, uncached["a.txt"], hashes["a.txt"]) +} + +// A file that the index tracks is part of the working tree even below a +// folder that a later .gitignore rule excludes, as for git status. Edits of it +// are attributed. +func TestSnapshotWorktree_TrackedFilesBelowExcludedFolder(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git binary not found") + } + root := t.TempDir() + run := func(args ...string) { + cmd := exec.Command("git", args...) + cmd.Dir = root + out, err := cmd.CombinedOutput() + require.NoError(t, err, "git %v: %s", args, out) + } + run("init", "-b", "main") + run("config", "user.email", "t@t.com") + run("config", "user.name", "t") + + writeTestFile(t, root, "vendor/tracked.go", "package vendor\n") + writeTestFile(t, root, "vendor/sub/tracked.go", "package sub\n") + run("add", ".") + run("commit", "-m", "init") + // The folder is ignored after its files were committed. + writeTestFile(t, root, ".gitignore", "vendor/\nbuild/\n") + writeTestFile(t, root, "vendor/untracked.go", "package vendor\n") + writeTestFile(t, root, "build/out.bin", "artifact\n") + + rec := &recordingFS{Filesystem: osfs.New(root)} + hashes, _, err := snapshotWorktree(rec, root, nil, time.Now()) + require.NoError(t, err) + + assert.Contains(t, hashes, "vendor/tracked.go") + assert.Contains(t, hashes, "vendor/sub/tracked.go") + assert.NotContains(t, hashes, "vendor/untracked.go") + assert.NotContains(t, hashes, "build/out.bin") + for _, p := range rec.paths { + assert.NotContains(t, p, "vendor", "no ignore rules are read below an excluded folder") + } +} + // A snapshot that takes its hashes from the cache holds what a snapshot // without a cache holds. func TestSnapshotWorktreeCached_MatchesUncachedSnapshot(t *testing.T) { diff --git a/app/cli/pkg/action/trace_agent_hook.go b/app/cli/pkg/action/trace_agent_hook.go index c2dfdaeeb..6e139d682 100644 --- a/app/cli/pkg/action/trace_agent_hook.go +++ b/app/cli/pkg/action/trace_agent_hook.go @@ -638,11 +638,12 @@ func registerCommandCheckouts(provider trace.Provider, input *trace.HookInput, h } } -// insideGitDir reports whether dir is a .git folder or a folder below one. A -// path there resolves to the repository of that folder, but a tool that works -// there does not work in its checkout. -func insideGitDir(dir string) bool { - return slices.Contains(strings.Split(filepath.ToSlash(filepath.Clean(dir)), "/"), ".git") +// insideGitDir reports whether p is a .git entry (a folder, or the file of a +// linked worktree) or a path below one. A path there resolves to the +// repository of that entry, but a tool that works there does not work in its +// checkout. +func insideGitDir(p string) bool { + return slices.Contains(strings.Split(filepath.ToSlash(filepath.Clean(p)), "/"), ".git") } // sameDir reports whether a and b name the same directory, ignoring symlinks @@ -770,9 +771,10 @@ func recordTranscriptPath(store *state.Store, rec *state.SessionRecord, transcri // session there. func locateForHook(provider trace.Provider, input *trace.HookInput) (*state.Store, string, error) { if input.FilePath != "" && provider.IsFileWritingTool(input.ToolName) { - // A file inside a .git folder (info/exclude, a hook) is not a file - // of the checkout, and its repository must not join the session. - if insideGitDir(filepath.Dir(input.FilePath)) { + // The .git file of a linked worktree, or a file inside a .git + // folder (info/exclude, a hook), is not a file of the checkout, and + // its repository must not join the session. + if insideGitDir(input.FilePath) { return nil, "", fmt.Errorf("%s is inside a .git folder, not in a checkout", input.FilePath) } diff --git a/app/cli/pkg/action/trace_shell_checkout_test.go b/app/cli/pkg/action/trace_shell_checkout_test.go index f3abf7a4f..01c1603af 100644 --- a/app/cli/pkg/action/trace_shell_checkout_test.go +++ b/app/cli/pkg/action/trace_shell_checkout_test.go @@ -267,6 +267,8 @@ func TestLocateForHook_FileInsideGitFolder(t *testing.T) { other := resolvedTempGitRepo(t) for _, file := range []string{ + // The .git file of a linked worktree. + filepath.Join(other, ".git"), filepath.Join(other, ".git", "info", "exclude"), filepath.Join(other, ".git", "worktrees", "wt", "HEAD"), } {