diff --git a/internal/library/skillcheck.go b/internal/library/skillcheck.go index 751671dfc..365f83aa3 100644 --- a/internal/library/skillcheck.go +++ b/internal/library/skillcheck.go @@ -199,9 +199,18 @@ func apiGet(u string) ([]byte, int, bool, error) { func hashDir(dir string) string { return hashFiles(dir, false) } // hashFiles is hashDir, leaving aside the .DS_Store files Finder leaves in -// a folder it shows when noFinder is set. +// a folder it shows when noFinder is set. A folder unchanged since it was +// last hashed isn't read again (treememo.go). func hashFiles(dir string, noFinder bool) string { + return rememberedHash(dir, noFinder) +} + +// hashWalk walks dir as hashFiles reads it, stamping each file and link +// it would hash (treememo.go); with read, it also hashes their bytes. ok +// is false when it can't be walked, or a file can't be read. +func hashWalk(dir string, noFinder, read bool) (hash, stamp string, settled, ok bool) { h := sha256.New() + st := newStamper() err := filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { if err != nil { return err @@ -214,15 +223,30 @@ func hashFiles(dir string, noFinder bool) string { return filepath.SkipDir } case d.Type()&fs.ModeSymlink != 0: - t, _ := os.Readlink(p) - fmt.Fprintf(h, "link %s %s\n", rel, filepath.ToSlash(t)) + fi, err := d.Info() + if err != nil { + return err + } + st.add(rel, fi) + if read { + t, _ := os.Readlink(p) + fmt.Fprintf(h, "link %s %s\n", rel, filepath.ToSlash(t)) + } case d.Type().IsRegular() && rel != marker && !(noFinder && d.Name() == ".DS_Store"): + fi, err := d.Info() + if err != nil { + return err + } + st.add(rel, fi) + if !read { + return nil + } f, err := os.Open(p) if err != nil { return err } defer f.Close() - fi, _ := f.Stat() + fi, _ = f.Stat() fmt.Fprintf(h, "file %s %d\n", rel, fi.Size()) if _, err := io.Copy(h, f); err != nil { return err @@ -231,9 +255,13 @@ func hashFiles(dir string, noFinder bool) string { return nil }) if err != nil { - return "" + return "", "", false, false } - return hex.EncodeToString(h.Sum(nil)) + stamp, settled = st.done() + if read { + hash = hex.EncodeToString(h.Sum(nil)) + } + return hash, stamp, settled, true } func firstLine(s string) string { diff --git a/internal/library/skills.go b/internal/library/skills.go index c2ad81a88..8b3aa0f19 100644 --- a/internal/library/skills.go +++ b/internal/library/skills.go @@ -1564,6 +1564,9 @@ func foundSkills(l *Library) []FoundSkill { places = append(places, place{dir: t.Skills, agent: t.Agent.ID}) } } + // a skill in several agents is compared with the first found, which + // is walked once + seen := walked{} for _, pl := range places { es, _ := os.ReadDir(pl.dir) for _, e := range es { @@ -1605,7 +1608,7 @@ func foundSkills(l *Library) []FoundSkill { case pl.agent == "": // another by that name in the shared folder than the one in // the library's: no agent's, and left as it is - case sameTree(p, f.at): + case sameTreeIn(seen, p, f.at): f.Copies = append(f.Copies, pl.agent) default: f.Others = append(f.Others, pl.agent) @@ -1869,23 +1872,63 @@ func setAside(agent, p string) (string, error) { // sameTree is whether two skill folders (links followed) hold the same // files with the same bytes, leaving aside what Finder or version control // keeps in one (.DS_Store, .git) and the mark on magpie's own copy. -func sameTree(a, b string) bool { +// Two folders unchanged since they were last compared aren't read again +// (treememo.go). +func sameTree(a, b string) bool { return sameTreeIn(nil, a, b) } + +// walked is the folders one pass has walked (treeOf), for a folder +// compared with several others to be walked once in it. +type walked map[string]*tree + +// sameTreeIn is sameTree, taking a folder walked already in this pass +// from w (nil: none). +func sameTreeIn(w walked, a, b string) bool { a, b = realDir(a), realDir(b) - fa, okA := treeOf(a) - fb, okB := treeOf(b) - if !okA || !okB || len(fa) != len(fb) { + look := func(d string) (tree, bool) { + if t, ok := w[d]; ok { + if t == nil { + return tree{}, false + } + return *t, true + } + t, ok := treeOf(d) + if w != nil { + if ok { + w[d] = &t + } else { + w[d] = nil + } + } + return t, ok + } + ta, okA := look(a) + tb, okB := look(b) + if !okA || !okB { + // unknown: not the same, and not kept as different return false } + return rememberedSame(a, b, ta, tb, func() (bool, bool) { return compareTrees(a, b, ta.files, tb.files) }) +} + +// compareTrees is sameTree, reading every file of both. sure is false +// when one couldn't be read whole: they aren't taken to be the same, and +// that isn't kept as what they are. +func compareTrees(a, b string, fa, fb map[string]treeEntry) (same, sure bool) { + if len(fa) != len(fb) { + return false, true + } for rel, x := range fa { y, ok := fb[rel] if !ok || x != y { - return false + return false, true } - if x.link == "" && !sameFile(filepath.Join(a, rel), filepath.Join(b, rel)) { - return false + if x.link == "" { + if same, sure := sameFile(filepath.Join(a, rel), filepath.Join(b, rel)); !same { + return false, sure + } } } - return true + return true, true } type treeEntry struct { @@ -1893,10 +1936,19 @@ type treeEntry struct { link string // where a link in it points } -// treeOf is a folder's files and links by where they are in it; not ok -// when it can't be read, or is too big to be worth comparing. -func treeOf(root string) (map[string]treeEntry, bool) { +// tree is a folder's files and links by where they are in it, and the +// stamp of them (treememo.go), from one walk that opens no file. +type tree struct { + files map[string]treeEntry + stamp string + settled bool +} + +// treeOf is a folder's files and links; not ok when it can't be read, or +// is too big to be worth comparing. +func treeOf(root string) (tree, bool) { out := map[string]treeEntry{} + st := newStamper() var total int64 err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { if err != nil { @@ -1918,6 +1970,10 @@ func treeOf(root string) (map[string]treeEntry, bool) { return nil } rel, _ := filepath.Rel(root, p) + fi, err := d.Info() + if err != nil { + return err + } if d.Type()&fs.ModeSymlink != 0 { to, err := os.Readlink(p) if err != nil { @@ -1925,41 +1981,50 @@ func treeOf(root string) (map[string]treeEntry, bool) { } out[rel] = treeEntry{link: to} } else if d.Type().IsRegular() { - fi, err := d.Info() - if err != nil { - return err - } out[rel] = treeEntry{size: fi.Size()} total += fi.Size() + } else { + return nil } + st.add(rel, fi) if len(out) > 20000 || total > 256<<20 { return errors.New("too big to compare") } return nil }) - return out, err == nil + if err != nil { + return tree{}, false + } + stamp, settled := st.done() + return tree{files: out, stamp: stamp, settled: settled}, true } -func sameFile(a, b string) bool { +// sameFile is whether a and b hold the same bytes; sure is false when one +// couldn't be read. +func sameFile(a, b string) (same, sure bool) { fa, err := os.Open(a) if err != nil { - return false + return false, false } defer fa.Close() fb, err := os.Open(b) if err != nil { - return false + return false, false } defer fb.Close() ba, bb := make([]byte, 64<<10), make([]byte, 64<<10) + end := func(e error) bool { return e == io.EOF || e == io.ErrUnexpectedEOF } for { na, ea := io.ReadFull(fa, ba) nb, eb := io.ReadFull(fb, bb) + if ea != nil && !end(ea) || eb != nil && !end(eb) { + return false, false + } if na != nb || !bytes.Equal(ba[:na], bb[:nb]) { - return false + return false, true } if ea != nil || eb != nil { - return ea == eb || (ea == io.EOF || ea == io.ErrUnexpectedEOF) && (eb == io.EOF || eb == io.ErrUnexpectedEOF) + return end(ea) && end(eb), true } } } diff --git a/internal/library/treememo.go b/internal/library/treememo.go new file mode 100644 index 000000000..6ec3f2305 --- /dev/null +++ b/internal/library/treememo.go @@ -0,0 +1,117 @@ +package library + +// Reading the Library page compares skill folders whole: an agent's own +// skill against the same name in another agent (foundSkills), and each +// agent's copy against the library's skill (behind). Each compare read +// every byte of both folders on every read of the page, so a few dozen +// skills with node_modules or templates in them, given to several agents, +// read hundreds of megabytes each time the page opened; on Windows, with +// every file read scanned, that is minutes (0day404, #541). What a compare +// or a hash found is kept here against what a walk of the folders sees +// without opening a file: each entry's place, size and time. While those +// are the same, the answer is too. A folder that couldn't be walked or +// read whole is unknown: it is read again next time, never taken as +// unchanged. + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + stdhash "hash" + "io/fs" + "path/filepath" + "sync" + "time" +) + +// settleFor is how long ago the newest file of a folder must have been +// written for what was found of it to be kept: a file written again within +// the time a file system can tell apart could keep its time and size. +const settleFor = 3 * time.Second + +// stamper sums what a walk sees of a folder's files and links without +// opening one: each one's place, type, size and time. The walk that reads +// a folder stamps it as it goes, before opening a file, so a file written +// while it is read has a stamp that says so next time. +type stamper struct { + h stdhash.Hash + newest time.Time +} + +func newStamper() *stamper { return &stamper{h: sha256.New()} } + +func (s *stamper) add(rel string, fi fs.FileInfo) { + fmt.Fprintf(s.h, "%s\x00%d\x00%d\x00%d\n", filepath.ToSlash(rel), fi.Mode().Type(), fi.Size(), fi.ModTime().UnixNano()) + if fi.ModTime().After(s.newest) { + s.newest = fi.ModTime() + } +} + +// done is the stamp, and whether nothing stamped was written in the last +// settleFor. +func (s *stamper) done() (stamp string, settled bool) { + return hex.EncodeToString(s.h.Sum(nil)), time.Since(s.newest) > settleFor +} + +type hashMemo struct{ stamp, hash string } + +type treeMemo struct { + a, b string + same bool +} + +var memo = struct { + sync.Mutex + hashes map[string]hashMemo // dir and noFinder: the folder's hash + trees map[[2]string]treeMemo // two folders: whether they hold the same +}{hashes: map[string]hashMemo{}, trees: map[[2]string]treeMemo{}} + +// rememberedHash is hashFiles(dir, noFinder): the hash found before, while +// a walk finds dir as it was then, else read. A folder hashed for the +// first time is walked once, as before the memo. +func rememberedHash(dir string, noFinder bool) string { + key := fmt.Sprintf("%t\x00%s", noFinder, dir) + memo.Lock() + m, hit := memo.hashes[key] + memo.Unlock() + if hit { + if _, stamp, _, ok := hashWalk(dir, noFinder, false); ok && stamp == m.stamp { + return m.hash + } + memo.Lock() + delete(memo.hashes, key) + memo.Unlock() + } + h, stamp, settled, ok := hashWalk(dir, noFinder, true) + if !ok { + return "" + } + if settled { + memo.Lock() + memo.hashes[key] = hashMemo{stamp: stamp, hash: h} + memo.Unlock() + } + return h +} + +// rememberedSame is whether trees a and b hold the same, as found before +// while both are as they were then, else compare. Only an answer from +// reading both whole (sure) is kept. +func rememberedSame(a, b string, ta, tb tree, compare func() (same, sure bool)) bool { + key := [2]string{a, b} + memo.Lock() + m, hit := memo.trees[key] + memo.Unlock() + if hit && m.a == ta.stamp && m.b == tb.stamp { + return m.same + } + same, sure := compare() + memo.Lock() + if sure && ta.settled && tb.settled { + memo.trees[key] = treeMemo{a: ta.stamp, b: tb.stamp, same: same} + } else { + delete(memo.trees, key) + } + memo.Unlock() + return same +} diff --git a/internal/library/treememo_test.go b/internal/library/treememo_test.go new file mode 100644 index 000000000..cac02766b --- /dev/null +++ b/internal/library/treememo_test.go @@ -0,0 +1,214 @@ +package library + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "io/fs" + "os" + "path/filepath" + "runtime" + "slices" + "strings" + "testing" + "time" +) + +// age sets every entry under dir to have been written an hour ago, as +// skills installed some other day are. +func age(t *testing.T, dir string) { + t.Helper() + then := time.Now().Add(-time.Hour) + var dirs []string + filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err == nil { + if d.IsDir() { + dirs = append(dirs, p) + } else if err := os.Chtimes(p, then, then); err != nil { + t.Fatal(err) + } + } + return nil + }) + // a folder's time is its own, set last, deepest first + for _, p := range slices.Backward(dirs) { + if err := os.Chtimes(p, then, then); err != nil { + t.Fatal(err) + } + } +} + +// hide makes every file under dir but its SKILL.md (which says what the +// skill is) unreadable: a page read that opened one again couldn't tell +// what it holds. +func hide(t *testing.T, dir string) { + t.Helper() + filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() && d.Name() != "SKILL.md" { + fi, _ := d.Info() + os.Chmod(p, 0) + os.Chtimes(p, fi.ModTime(), fi.ModTime()) + } + return nil + }) + t.Cleanup(func() { + filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err == nil && !d.IsDir() { + os.Chmod(p, 0o644) + } + return nil + }) + }) +} + +func foundIn(t *testing.T, name string) FoundSkill { + t.Helper() + v, err := Read(nil) + if err != nil { + t.Fatal(err) + } + for _, f := range v.FoundSkills { + if f.Name == name { + return f + } + } + t.Fatalf("%s not found: %+v", name, v.FoundSkills) + return FoundSkill{} +} + +// The Library page compared an agent's own skill with the same name in +// another agent byte by byte on every read, and with big skills in many +// agents that took minutes each time the page opened (0day404, #541). A +// read of folders unchanged since the last one doesn't open their files +// again, and says what it said then; a folder written since is read again. +func TestPageReadDoesntReadUnchangedSkillsAgain(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a file can't be made unreadable with a mode on Windows") + } + if os.Geteuid() == 0 { + t.Skip("root reads a file whatever its mode") + } + h := sandbox(t) + big := strings.Repeat("template ", 4096) + for _, d := range []string{".claude/skills/deck", ".codex/skills/deck"} { + skill(t, filepath.Join(h, d), "deck", "Slides") + write(t, filepath.Join(h, d, "assets/template.txt"), big) + age(t, filepath.Join(h, d)) + } + codex := filepath.Join(h, ".codex/skills/deck") + if f := foundIn(t, "deck"); !slices.Contains(f.Copies, "codex") { + t.Fatalf("codex's deck holds the same files as Claude Code's: %+v", f) + } + hide(t, codex) + if f := foundIn(t, "deck"); !slices.Contains(f.Copies, "codex") { + t.Fatalf("a second read opened codex's files again: %+v", f) + } + + // written since: read again, and found to differ + os.Chmod(filepath.Join(codex, "SKILL.md"), 0o644) + os.Chmod(filepath.Join(codex, "assets/template.txt"), 0o644) + write(t, filepath.Join(codex, "assets/template.txt"), strings.Replace(big, "template", "Template", 1)) + if f := foundIn(t, "deck"); slices.Contains(f.Copies, "codex") || !slices.Contains(f.Others, "codex") { + t.Fatalf("codex's deck was edited: %+v", f) + } +} + +// What was found of a folder written a moment ago isn't kept: a file +// written again within the time its file system tells apart could keep +// its size and time. +func TestJustWrittenSkillIsReadAgain(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a file can't be made unreadable with a mode on Windows") + } + if os.Geteuid() == 0 { + t.Skip("root reads a file whatever its mode") + } + h := sandbox(t) + for _, d := range []string{".claude/skills/deck", ".codex/skills/deck"} { + skill(t, filepath.Join(h, d), "deck", "Slides") + } + if f := foundIn(t, "deck"); !slices.Contains(f.Copies, "codex") { + t.Fatalf("same files: %+v", f) + } + hide(t, filepath.Join(h, ".codex/skills/deck")) + if f := foundIn(t, "deck"); slices.Contains(f.Copies, "codex") { + t.Fatalf("a folder written a moment ago was taken as read: %+v", f) + } +} + +// A folder that couldn't be read whole isn't remembered as different: +// once it can be read, it is compared again. +func TestUnreadableSkillIsntRememberedAsDifferent(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a file can't be made unreadable with a mode on Windows") + } + if os.Geteuid() == 0 { + t.Skip("root reads a file whatever its mode") + } + h := sandbox(t) + for _, d := range []string{".claude/skills/deck", ".codex/skills/deck"} { + skill(t, filepath.Join(h, d), "deck", "Slides") + age(t, filepath.Join(h, d)) + } + // not SKILL.md: a skill whose SKILL.md can't be read isn't listed at all + run := filepath.Join(h, ".codex/skills/deck/scripts/run.sh") + fi, _ := os.Stat(run) + os.Chmod(run, 0) + os.Chtimes(run, fi.ModTime(), fi.ModTime()) + if f := foundIn(t, "deck"); slices.Contains(f.Copies, "codex") { + t.Fatalf("an unreadable folder was taken as the same: %+v", f) + } + os.Chmod(run, 0o644) + if f := foundIn(t, "deck"); !slices.Contains(f.Copies, "codex") { + t.Fatalf("readable again, it's the same: %+v", f) + } +} + +// A library skill edited some time ago, after a read that hashed it, is +// hashed again: its copies are said to be behind it, though every file +// of it was written long before the page is read. +func TestEditedLibrarySkillIsHashedAgain(t *testing.T) { + h := sandbox(t) + src := filepath.Join(h, "src/skills") + skill(t, filepath.Join(src, "pdf"), "pdf", "Read PDFs") + ok(t)(InstallSkills(src, []string{"pdf"}, []string{"claude", "codex"})) + ok(t)(SetSkillHow("", HowCopy)) + age(t, h) + v, err := Read(nil) + if err != nil || v.Skills[0].Behind != nil { + t.Fatalf("behind at once: %+v %v", v.Skills, err) + } + // the same size, an hour ago: only the time tells it changed + md := filepath.Join(skillDir("pdf"), "SKILL.md") + write(t, md, strings.Replace(read(t, md), "Read PDFs", "Read PDFS", 1)) + age(t, skillDir("pdf")) + if v, _ = Read(nil); !slices.Equal(v.Skills[0].Behind, []string{"claude", "codex"}) { + t.Fatalf("the library's skill changed, and its copies aren't behind: %v", v.Skills[0].Behind) + } +} + +// What hashFiles says of a folder is what it said before the memo: the +// hashes are kept in the library and in each copy's mark. +func TestHashUnchangedByTheMemo(t *testing.T) { + d := t.TempDir() + write(t, filepath.Join(d, "SKILL.md"), "---\nname: x\n---\n") + write(t, filepath.Join(d, "scripts/run.sh"), "echo hi\n") + write(t, filepath.Join(d, ".DS_Store"), "finder") + write(t, filepath.Join(d, ".git/HEAD"), "ref") + if err := os.Symlink("scripts/run.sh", filepath.Join(d, "run")); err != nil { + t.Skip(err) + } + sum := func(noFinder bool) string { + x := sha256.New() + if !noFinder { + fmt.Fprintf(x, "file .DS_Store 6\nfinder") + } + fmt.Fprintf(x, "file SKILL.md 16\n---\nname: x\n---\nlink run scripts/run.sh\nfile scripts/run.sh 8\necho hi\n") + return hex.EncodeToString(x.Sum(nil)) + } + for _, nf := range []bool{false, true} { + if got := hashFiles(d, nf); got != sum(nf) { + t.Errorf("noFinder %v: %s, want %s", nf, got, sum(nf)) + } + } +}