From 73ecef0b36cd8a3467eb70fbdd9799ea98db9b7d Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 14 Nov 2026 14:23:30 +0800 Subject: [PATCH] memory: each memory is a Markdown file of its own memory.json held every memory in one JSON file, which grew without bound, was hard to read or fix by hand, and was rewritten whole on every change. Memory is now a folder, `memory/` beside where memory.json was: - `.md` is the memory: YAML front matter (kind, scope, status, origin, pinned, tags, why, sources, times) and the text as the body. The file is the source of truth. - `meta.json` holds what isn't one memory's: projects, the digest, dismissed texts, deletions, declined suggestions, when a search last returned each memory (so a search never rewrites a memory's file), and the hash of each file as magpie last wrote it. - `index.json` is a cache of the parsed files by size and mtime only: deleted or garbled, memory reads the same. - `journal.json` holds a change to more than one file (a merge, a sync) before any is written; the next read finishes one cut off halfway. A file whose hash isn't the one magpie wrote was edited or added by hand: it is the user's (origin user, Edited), so a tidy leaves it and an agent's change synced from another computer never writes over it. A file with no front matter is a global fact named by its file. A write leaves any file that changed on disk since it was read (a hand edit made meanwhile), and so does a remove. A file that can't be parsed is left out and never written over nor removed, sync included; meta.json that can't be read is unknown (an error), as memory.json was. memory.json is moved in on the first read, all under one journal, and kept as memory.json.migrated. One that can't be read is an error and nothing is written. The scope of a hand-written file keeps its case (a project's holds a path); "global" in any case is global. Ran at this head (rebased on origin/main 50d88f17c), on mote: - go test -count=1 ./internal/memory ./internal/memdistill ./internal/memembed ./internal/backup ./internal/library ./internal/gui: ./internal/davsync ./internal/appdir: ok; go vet ./internal/...: ok; go test -run 'Memory|memory|Doc|Subsystem' ./internal/...: 98 ok - go vet ./... and GOOS=windows go vet ./... (before the rebase, whose three commits touch no memory code): ok; gofmt -l: clean - win-run go test ./internal/memory ./internal/backup: ok - wsl-run go vet of memory, backup, library, memdistill, memembed, davsync and go test of memory, backup, memdistill: ok - A copy of the real memory.json (206 memories) migrated in a sandbox: every field of every memory the same on the first read, from the index, and with the index rebuilt; no memory read as the user's. Broken by hand, each red, green restored: - no journal: TestCutOffChangeIsFinished - no on-disk hash check on write: TestHandEditDuringAChangeStays - no on-disk hash check on remove: TestHandEditDuringARemoveStays - broken files written: TestBrokenFileIsLeftAsItIs - no hand-edit detection: TestHandEditIsTheUsers - scope lowercased: TestEachMemoryIsAMarkdownFile (and memdistill's TestReadsQuietSessionsOnce, which found it) Not tried: the full go test ./... (mote and mica both over their cores); the live app's own memory moved in (a sandbox copy only); `go vet ./...` on Linux (the WSL box has no gtk4 headers for Wails); a hand edit through a sync service's own conflict copies. --- docs/subsystems/memory.md | 53 ++- docs/subsystems/sync-backup.md | 3 +- internal/backup/backup.go | 2 +- internal/backup/memory_test.go | 16 +- internal/library/instructions.go | 2 +- internal/library/memory_digest_test.go | 19 +- internal/memory/digest.go | 2 +- internal/memory/memory.go | 135 +----- internal/memory/memory_test.go | 27 +- internal/memory/store.go | 598 +++++++++++++++++++++++++ internal/memory/store_test.go | 303 +++++++++++++ internal/memory/sync.go | 16 +- 12 files changed, 1013 insertions(+), 163 deletions(-) create mode 100644 internal/memory/store.go create mode 100644 internal/memory/store_test.go diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index 47876e6e9..dc1ff38c8 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -8,14 +8,47 @@ Library → Instructions, and the Library's Memory tab. ## Source of truth -`memory.json` in magpie's config folder ([internal/memory/memory.go](../../internal/memory/memory.go)). +The `memory` folder in magpie's config folder, one Markdown file per memory +([internal/memory/store.go](../../internal/memory/store.go)): -- One writer at a time across magpies (`filelock`), written through a temp - file, the last good generation kept beside it (`lastgood`). -- A file that can't be read is unknown, never empty: nothing is written - over it, searches fail, and `Digest` returns an error so the instructions - keep what the agent has (`TestUnreadableFileIsNeverWrittenOver`, - `TestCutShortFileReadFromItsBackup`). +- `.md` is the memory: its fields as YAML front matter, its text as the + body. The file is the memory; everything else is beside it. +- `meta.json` holds what isn't one memory's: projects, the published + digest, dismissed texts, deletions, declined suggestions, when a search + last returned each memory and how often (so a search never rewrites a + memory's file, `TestUseDoesNotRewriteTheMemory`), and the hash of each + file as magpie last wrote it. +- `index.json` is a cache of the parsed files by size and mtime: gone or + garbled, memory reads the same (`TestIndexIsOnlyACache`). +- `journal.json` holds a change to more than one file (a merge, a sync) + before any is written; a change cut off halfway is finished by the next + read (`TestCutOffChangeIsFinished`). A journal that can't be read is an + error. + +Rules: + +- One writer at a time across magpies (`filelock`, `memory.lock`), each file + written through a temp file, and only the files that changed. The last + good meta.json is kept beside it (`lastgood`). +- A file whose hash isn't the one magpie wrote was edited (or added) by + hand: it is the user's (origin user, `Edited`), so a tidy leaves it and an + agent's change synced from another computer never writes over it + (`TestHandEditIsTheUsers`). A file with no front matter is a fact that + holds everywhere, its name its id (`TestHandAddedFileIsAMemory`). A file + edited by hand while magpie changes or removes it is left as the user + wrote it (`TestHandEditDuringAChangeStays`, + `TestHandEditDuringARemoveStays`). +- A memory file that can't be parsed is unknown: left out, never written + over nor removed, sync included, and read again once fixed + (`TestBrokenFileIsLeftAsItIs`). A meta.json that can't be read is + unknown, never empty: nothing is written, searches fail, and `Digest` + returns an error so the instructions keep what the agent has + (`TestUnreadableFileIsNeverWrittenOver`, + `TestCutShortMetaReadFromItsBackup`). +- `memory.json`, where memory was kept before, is moved into the folder on + the first read, all of it under one journal, and kept as + `memory.json.migrated` (`TestMemoryJSONIsMovedIn`). One that can't be + read is an error, and nothing is written. A memory is one short text (`MaxText` runes) with: @@ -161,7 +194,7 @@ further (`State.Since`), unless a range is picked. and the row says how many (`State.Left`) (`TestBacklogReadAtOnce`, `TestStopEndsTheRun`). Before, every run read 10, and 400 took 40 hours (RealZeroP27 on X). -- State is `distill.json` beside `memory.json` (`memdistill.Path`): +- State is `distill.json` beside the `memory` folder (`memdistill.Path`): the switch, the model, the reasoning level, the range, the conversations done, and the last run's time, counts, error and how many it left. A @@ -307,14 +340,14 @@ meaning, since it downloads a model (~135 MB). Memory goes to another computer in a backup file (the scheduled backups too) and in sync (WebDAV, S3, GitHub), merged memory by memory, never one -computer's memory.json over the other's. +computer's memory over the other's. [sync.go](../../internal/memory/sync.go) owns it. - What goes (`memory.Bundle`, `Collect`): the memories in every state, the projects, the dismissed distilled texts, the suggestions turned down and the deletions. The digest published into the agents' instructions and the vectors (memembed) are this computer's own and are made again after a - change. A memory.json that can't be read stops the backup or sync instead + change. Memory that can't be read stops the backup or sync instead of going as no memory (`TestCollectUnreadableIsAnError`, `TestCollectStopsOnUnreadableMemory`). - Merging (`Combine`, the same either way round): of two copies of one diff --git a/docs/subsystems/sync-backup.md b/docs/subsystems/sync-backup.md index f83cba712..5eea0a68d 100644 --- a/docs/subsystems/sync-backup.md +++ b/docs/subsystems/sync-backup.md @@ -185,7 +185,8 @@ repository and `magpie github upload`, rather than WebDAV's recovery path. A local file that is there but can't be read is unknown, never empty or the defaults. `backup.Collect` stops on an unreadable providers.json (with its groups and order), settings.json (`settings.LoadChecked`: unreadable, or -not parsing with no good `.bak`) or library.json, and on a gateway key +not parsing with no good `.bak`), library.json or memory (its meta.json, see +[Memory](memory.md#source-of-truth)), and on a gateway key store that fails to export. A backup, an export and a sync all end with that error, nothing sealed or pushed; the sync's status shows it. A missing or empty settings.json is still none (`TestCollectStopsOnUnreadableSettings`, diff --git a/internal/backup/backup.go b/internal/backup/backup.go index 30098294d..922e9333a 100644 --- a/internal/backup/backup.go +++ b/internal/backup/backup.go @@ -293,7 +293,7 @@ func Collect(keys bool, app string) (Bundle, error) { if !keys && b.Library != nil { b.Library.WithoutSecrets(Secret) } - // a memory.json that can't be read stops it too: unknown, not none + // memory that can't be read stops it too: unknown, not none if b.Memory, err = memory.Collect(); err != nil { return b, fmt.Errorf("memory: %w", err) } diff --git a/internal/backup/memory_test.go b/internal/backup/memory_test.go index f2f281385..a9de383ea 100644 --- a/internal/backup/memory_test.go +++ b/internal/backup/memory_test.go @@ -2,6 +2,7 @@ package backup import ( "os" + "path/filepath" "strings" "testing" @@ -73,7 +74,7 @@ func TestBackupMergesMemory(t *testing.T) { } } -// A memory.json that can't be read stops the backup: carried as no +// Memory that can't be read stops the backup: carried as no // memory, it would say there was none. func TestCollectStopsOnUnreadableMemory(t *testing.T) { home(t) @@ -81,16 +82,17 @@ func TestCollectStopsOnUnreadableMemory(t *testing.T) { if b, err := Collect(true, "test"); err != nil || b.Memory == nil || len(b.Memory.Memories) != 1 { t.Fatalf("collect: %+v, %v", b.Memory, err) } - if err := os.WriteFile(memory.Path(), []byte(`{"memories":[{"id":"m_1`), 0o600); err != nil { + meta := filepath.Join(memory.Dir(), "meta.json") + if err := os.WriteFile(meta, []byte(`{"projects":{"p`), 0o600); err != nil { t.Fatal(err) } - os.Remove(lastgood.Bak(memory.Path())) + os.Remove(lastgood.Bak(meta)) if _, err := Collect(true, "test"); err == nil || !strings.Contains(err.Error(), "memory") { - t.Fatalf("Collect read a memory.json that can't be read: %v", err) + t.Fatalf("Collect read memory that can't be read: %v", err) } - // and no memory.json is no memory, not an error - os.Remove(memory.Path()) + // and no memory is no memory, not an error + os.RemoveAll(memory.Dir()) if b, err := Collect(true, "test"); err != nil || b.Memory != nil { - t.Fatalf("no memory.json: %+v, %v", b.Memory, err) + t.Fatalf("no memory: %+v, %v", b.Memory, err) } } diff --git a/internal/library/instructions.go b/internal/library/instructions.go index 9af52f39a..4ad63ba8c 100644 --- a/internal/library/instructions.go +++ b/internal/library/instructions.go @@ -162,7 +162,7 @@ func (l *Library) wanted(agent string) string { } // memoryDigest is memory's published digest for the agent, "" when -// NoMemory, or memory.json can't be read (syncInstructions writes nothing +// NoMemory, or memory can't be read (syncInstructions writes nothing // then: unknown, not empty). func (l *Library) memoryDigest(id string) string { if l.Instructions.NoMemory { diff --git a/internal/library/memory_digest_test.go b/internal/library/memory_digest_test.go index 613efff06..487b56e7d 100644 --- a/internal/library/memory_digest_test.go +++ b/internal/library/memory_digest_test.go @@ -18,7 +18,7 @@ func memSave(t *testing.T, text, kind, scope string) { // Memory's published digest is written into a ticked agent's part after // the shared text, with what is kept for that agent alone; an agent not -// ticked gets none. A save shows only once published, and a memory.json +// ticked gets none. A save shows only once published, and memory // that can't be read leaves the part as it was (unknown, not empty). // NoMemory leaves the digest out. func TestMemoryDigestInInstructions(t *testing.T) { @@ -29,8 +29,8 @@ func TestMemoryDigestInInstructions(t *testing.T) { if res, err := PublishMemory(true); err != nil || res != nil { t.Fatalf("nothing kept, but published: %+v %v", res, err) } - if _, err := os.Stat(memory.Path()); err == nil { - t.Fatal("a due publish with nothing kept wrote memory.json") + if _, err := os.Stat(memory.Dir()); err == nil { + t.Fatal("a due publish with nothing kept wrote memory") } memSave(t, "Answer in Chinese.", memory.Preference, memory.Global) @@ -51,26 +51,27 @@ func TestMemoryDigestInInstructions(t *testing.T) { t.Errorf("claude isn't ticked, but was given memory:\n%s", readMaybe(c)) } - // memory.json unreadable: the part is left as it is + // memory unreadable: the part is left as it is memSave(t, "Use tabs.", memory.Preference, memory.Global) if _, err := memory.Publish(); err != nil { t.Fatal(err) } - if err := os.WriteFile(memory.Path(), []byte("{not json"), 0o600); err != nil { + meta := filepath.Join(memory.Dir(), "meta.json") + if err := os.WriteFile(meta, []byte("{not json"), 0o600); err != nil { t.Fatal(err) } - os.Remove(memory.Path() + ".bak") + os.Remove(meta + ".bak") res, err := changeInstructions(func(*Library) error { return nil }) if err != nil { t.Fatal(err) } if got := read(t, codex); got != s { - t.Fatalf("an unreadable memory.json changed the part:\n%s", got) + t.Fatalf("unreadable memory changed the part:\n%s", got) } if len(res.Problems) == 0 { - t.Errorf("an unreadable memory.json wasn't said: %+v", res) + t.Errorf("unreadable memory wasn't said: %+v", res) } - if err := os.Remove(memory.Path()); err != nil { + if err := os.RemoveAll(memory.Dir()); err != nil { t.Fatal(err) } diff --git a/internal/memory/digest.go b/internal/memory/digest.go index 64212c246..57c61130a 100644 --- a/internal/memory/digest.go +++ b/internal/memory/digest.go @@ -147,7 +147,7 @@ func PublishDue() (bool, error) { // Digest is the published digest an agent is given: the global part, the // agent's own, and each project's under the folders it was seen in, held // to the whole budget, the projects with the newest memories first. "" -// when there is nothing, or memory.json can't be read (unknown: the +// when there is nothing, or memory can't be read (unknown: the // caller keeps what the agent has). func Digest(agent string) (string, error) { f, err := cached() diff --git a/internal/memory/memory.go b/internal/memory/memory.go index 451016ac1..65c19cb5d 100644 --- a/internal/memory/memory.go +++ b/internal/memory/memory.go @@ -7,31 +7,21 @@ // user picks are also given a digest of it in their instructions // (library/instructions.go). The Library's Memory tab lists and edits it. // -// It is memory.json in magpie's config folder: one writer at a time across -// magpies (filelock), written through a temp file, the last good -// generation kept beside it, and a file that can't be read is unknown, -// never empty, so nothing is written over it. +// It is a folder of Markdown files in magpie's config folder, one a memory +// (store.go): one writer at a time across magpies (filelock), a change to +// several written all or none (a journal), and a file that can't be read +// is unknown, never empty, so nothing is written over it. package memory import ( "crypto/rand" "encoding/hex" - "encoding/json" "errors" "fmt" - "io/fs" - "os" - "path/filepath" "slices" "strings" - "sync" "time" "unicode/utf8" - - "github.com/yetone/magpie/internal/appdir" - "github.com/yetone/magpie/internal/edit" - "github.com/yetone/magpie/internal/filelock" - "github.com/yetone/magpie/internal/lastgood" ) // The kinds of memory. A kind decides how long a memory stays true and @@ -118,7 +108,7 @@ type Project struct { Roots []string `json:"roots,omitempty"` } -// file is memory.json. +// file is all of memory as read from Dir (store.go). type file struct { Version int `json:"version"` Memories []*Memory `json:"memories"` @@ -140,6 +130,16 @@ type file struct { // Declined are the suggestions the user turned down (Suggest), by // key, the last maxDeclined Declined []string `json:"declined,omitempty"` + + // what read found on disk, for write to change only what changed + // (store.go): each memory file's hash as read, the ids whose file + // can't be read (never written over nor removed), the hashes magpie + // last wrote (written: another is the user's edit), and meta.json's + // bytes + seen map[string]string + broken map[string]bool + written map[string]string + metaB []byte } // maxDismissed is how many dismissed texts are kept. @@ -161,74 +161,12 @@ func dismiss(f *file, m *Memory) { } } -// Path is memory.json; a variable for tests. -var Path = func() string { return appdir.Join(appdir.Config(), "memory.json") } - -var ( - mu = filelock.Mutex{Path: func() string { return Path() + ".lock" }} - // now is the clock; a variable for tests - now = time.Now -) +// now is the clock; a variable for tests +var now = time.Now // ErrNotFound is a memory id that isn't there. var ErrNotFound = errors.New("no memory with that id") -// read reads memory.json: empty when it isn't there, an error when it is -// and can't be read. -func read() (*file, error) { - f := &file{Version: 1} - b, err := lastgood.Read(Path(), lastgood.Into[file]) - if errors.Is(err, fs.ErrNotExist) { - return f, nil - } - if err != nil { - return nil, err - } - if err := json.Unmarshal(b, f); err != nil { - return nil, err - } - f.Memories = slices.DeleteFunc(f.Memories, func(m *Memory) bool { return m == nil || m.ID == "" }) - return f, nil -} - -func write(f *file) error { - p := Path() - if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { - return err - } - if err := lastgood.Keep(p, lastgood.Into[file], 0o600); err != nil { - return err - } - b, err := json.MarshalIndent(f, "", " ") - if err != nil { - return err - } - return edit.WriteAtomic(p, b) -} - -// change reads memory.json, lets fn change it and writes it, one magpie -// at a time. A file that can't be read is never written over. -func change(fn func(f *file) error) error { - mu.Lock() - defer mu.Unlock() - f, err := read() - if err != nil { - return err - } - if err := fn(f); err != nil { - return err - } - return write(f) -} - -// view reads memory.json under the lock, for a read that is consistent -// with the last write. -func view() (*file, error) { - mu.Lock() - defer mu.Unlock() - return read() -} - // All is every memory, in every state, newest change first, and the // projects they are kept for. func All() ([]*Memory, map[string]*Project, error) { @@ -604,42 +542,3 @@ func touch(ids []string) { return nil }) } - -// Modified is memory.json's modification time, zero when it isn't there: -// for a reader to tell whether it changed. -func Modified() time.Time { - st, err := os.Stat(Path()) - if err != nil { - return time.Time{} - } - return st.ModTime() -} - -// cache is memory.json as cached() last read it, and its modification time. -var cache struct { - sync.Mutex - at time.Time - f *file -} - -// cached is memory.json as last read, read again when it changed: for the -// digest, which a library sync reads for every agent. -func cached() (*file, error) { - cache.Lock() - defer cache.Unlock() - st, err := os.Stat(Path()) - if errors.Is(err, fs.ErrNotExist) { - return &file{Version: 1}, nil - } - if err == nil && cache.f != nil && st.ModTime().Equal(cache.at) { - return cache.f, nil - } - f, err := read() - if err != nil { - return nil, err - } - if st != nil { - cache.at, cache.f = st.ModTime(), f - } - return f, nil -} diff --git a/internal/memory/memory_test.go b/internal/memory/memory_test.go index 16d8bba7d..bedea808d 100644 --- a/internal/memory/memory_test.go +++ b/internal/memory/memory_test.go @@ -4,6 +4,7 @@ import ( "errors" "os" "path/filepath" + "slices" "strings" "testing" "time" @@ -38,12 +39,12 @@ func save(t *testing.T, text, kind, scope string, tags ...string) *Memory { func TestSaveKeepsTheLocalZone(t *testing.T) { at := fresh(t) *at = time.Date(2026, 11, 11, 4, 30, 0, 0, time.FixedZone("CST", 8*3600)) - save(t, "Answer in Chinese", Preference, Global) - b, err := os.ReadFile(Path()) + m := save(t, "Answer in Chinese", Preference, Global) + b, err := os.ReadFile(filepath.Join(Dir(), m.ID+".md")) if err != nil { t.Fatal(err) } - if !strings.Contains(string(b), `"updated": "2026-11-11T04:30:00+08:00"`) && !strings.Contains(string(b), `"updated":"2026-11-11T04:30:00+08:00"`) { + if !strings.Contains(string(b), "updated: \"2026-11-11T04:30:00+08:00\"") && !strings.Contains(string(b), "updated: 2026-11-11T04:30:00+08:00\n") { t.Fatalf("not saved in the local zone: %s", b) } } @@ -148,17 +149,25 @@ func TestUnreadableFileIsNeverWrittenOver(t *testing.T) { } } -// The last good generation is read when the file is cut short. -func TestCutShortFileReadFromItsBackup(t *testing.T) { +// meta.json cut short is read from its last good generation, and the +// memories are still each its own file. +func TestCutShortMetaReadFromItsBackup(t *testing.T) { fresh(t) save(t, "first", Fact, Global) - save(t, "second", Fact, Global) // keeps the first generation as .bak - if err := os.WriteFile(Path(), []byte(`{"memo`), 0o600); err != nil { + if err := Decline("k1"); err != nil { + t.Fatal(err) + } + save(t, "second", Fact, Global) // keeps the generation with k1 as .bak + if err := os.WriteFile(filepath.Join(Dir(), "meta.json"), []byte(`{"vers`), 0o600); err != nil { t.Fatal(err) } all, _, err := All() - if err != nil || len(all) != 1 || all[0].Text != "first" { - t.Fatalf("read %v, %v; want the backup's one memory", all, err) + if err != nil || len(all) != 2 { + t.Fatalf("read %v, %v; want both memories", all, err) + } + b, err := Collect() + if err != nil || !slices.Contains(b.Declined, "k1") { + t.Fatalf("meta not read from its backup: %+v %v", b, err) } } diff --git a/internal/memory/store.go b/internal/memory/store.go new file mode 100644 index 000000000..245db5af3 --- /dev/null +++ b/internal/memory/store.go @@ -0,0 +1,598 @@ +package memory + +// Memory is kept as a folder, Dir, beside where memory.json was: +// +// - .md, one a memory: its fields as YAML front matter, its text as +// the body. The file is the memory. One the user edits by hand is read +// as the user's change (Origin user, Edited: Fixed, so nothing a +// machine does writes over it), and one they add is a memory of +// theirs, its file name its id. +// - meta.json: what isn't one memory's. The projects, the published +// digests, the texts dismissed, the memories removed, the suggestions +// declined, when each memory was last used (so a search rewrites this +// file, not the memory's), and each memory file's hash as magpie last +// wrote it, which tells a hand edit from magpie's own. +// - index.json: each file's size, time, hash and what it says, so a +// read parses only the files that changed since. It is a cache, never +// read for what isn't in the files: deleted, it is made again. +// - journal.json, while a change to more than one file is written: +// every file the change writes, put down first, so a change cut off +// halfway is finished by the next read, never left half done. +// +// memory.json, from before, is moved into the folder on the first read +// (migrate) and kept as memory.json.migrated. + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io/fs" + "log" + "maps" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "time" + + "gopkg.in/yaml.v3" + + "github.com/yetone/magpie/internal/appdir" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/filelock" + "github.com/yetone/magpie/internal/lastgood" +) + +// Path is memory.json, where memory was kept before Dir; a variable for +// tests, which moves Dir with it. +var Path = func() string { return appdir.Join(appdir.Config(), "memory.json") } + +// Dir is the folder memory is kept in. +func Dir() string { return filepath.Join(filepath.Dir(Path()), "memory") } + +const ( + metaName = "meta.json" + indexName = "index.json" + journalName = "journal.json" +) + +func in(name string) string { return filepath.Join(Dir(), name) } + +var mu = filelock.Mutex{Path: func() string { return Dir() + ".lock" }} + +// meta is meta.json. +type meta struct { + Version int `json:"version"` + Projects map[string]*Project `json:"projects,omitempty"` + Digest map[string]string `json:"digest,omitempty"` + Published time.Time `json:"published,omitzero"` + Dismissed []string `json:"dismissed,omitempty"` + Removed map[string]time.Time `json:"removed,omitempty"` + Declined []string `json:"declined,omitempty"` + Used map[string]use `json:"used,omitempty"` + Written map[string]string `json:"written,omitempty"` +} + +// use is when a search last returned a memory, and how often. +type use struct { + At time.Time `json:"at"` + Uses int `json:"uses,omitempty"` +} + +// front is a memory file's front matter. +type front struct { + Kind string `yaml:"kind,omitempty"` + Scope string `yaml:"scope,omitempty"` + Status string `yaml:"status,omitempty"` + Origin string `yaml:"origin,omitempty"` + Pinned bool `yaml:"pinned,omitempty"` + Tags []string `yaml:"tags,omitempty,flow"` + Why string `yaml:"why,omitempty"` + SupersededBy string `yaml:"supersededBy,omitempty"` + Skill string `yaml:"skill,omitempty"` + Created string `yaml:"created,omitempty"` + Updated string `yaml:"updated,omitempty"` + Edited string `yaml:"edited,omitempty"` + Sources []source `yaml:"sources,omitempty"` +} + +type source struct { + Agent string `yaml:"agent,omitempty"` + Session string `yaml:"session,omitempty"` + Dir string `yaml:"dir,omitempty"` + File string `yaml:"file,omitempty"` + Quote string `yaml:"quote,omitempty"` + At string `yaml:"at,omitempty"` +} + +func stamp(t time.Time) string { + if t.IsZero() { + return "" + } + return t.Format(time.RFC3339Nano) +} + +// unstamp reads a time as magpie writes it, or as a person may: a date, or +// a date and time with no zone (local). +func unstamp(s string, or time.Time) (time.Time, error) { + s = strings.TrimSpace(s) + if s == "" { + return or, nil + } + if t, err := time.Parse(time.RFC3339Nano, s); err == nil { + return t, nil + } + for _, l := range []string{"2006-01-02 15:04:05", "2006-01-02T15:04:05", "2006-01-02 15:04", "2006-01-02"} { + if t, err := time.ParseInLocation(l, s, time.Local); err == nil { + return t, nil + } + } + return time.Time{}, fmt.Errorf("%q isn't a time", s) +} + +// encode is m's file. +func encode(m *Memory) ([]byte, error) { + fr := front{Kind: m.Kind, Scope: m.Scope, Status: m.Status, Origin: m.Origin, Pinned: m.Pinned, Tags: m.Tags, Why: m.Why, + SupersededBy: m.SupersededBy, Skill: m.Skill, Created: stamp(m.Created), Updated: stamp(m.Updated), Edited: stamp(m.Edited)} + for _, s := range m.Sources { + fr.Sources = append(fr.Sources, source{Agent: s.Agent, Session: s.Session, Dir: s.Dir, File: s.File, Quote: s.Quote, At: stamp(s.At)}) + } + var b bytes.Buffer + b.WriteString("---\n") + e := yaml.NewEncoder(&b) + e.SetIndent(2) + if err := e.Encode(fr); err != nil { + return nil, err + } + e.Close() + b.WriteString("---\n\n") + b.WriteString(m.Text) + b.WriteString("\n") + return b.Bytes(), nil +} + +// decode reads the file of the memory with id, changed at mod. What the +// front matter leaves out is what a memory the user adds is: a fact that +// holds everywhere, in use, theirs, made at mod. +func decode(id string, b []byte, mod time.Time) (*Memory, error) { + s := strings.TrimPrefix(strings.ReplaceAll(string(b), "\r\n", "\n"), "\ufeff") + var fr front + body := s + if rest, ok := strings.CutPrefix(s, "---\n"); ok { + var head string + switch i := strings.Index(rest, "\n---\n"); { + case strings.HasPrefix(rest, "---\n"): + head, body = "", rest[4:] + case i >= 0: + head, body = rest[:i], rest[i+5:] + case strings.HasSuffix(rest, "\n---"): + head, body = rest[:len(rest)-4], "" + default: + return nil, errors.New("its front matter has no closing ---") + } + if err := yaml.Unmarshal([]byte(head), &fr); err != nil { + return nil, fmt.Errorf("its front matter: %w", err) + } + } + m := &Memory{ID: id, Text: strings.TrimSpace(body), Kind: cmpOr(fr.Kind, Fact), Scope: scopeOf(fr.Scope), + Status: cmpOr(fr.Status, Active), Origin: cmpOr(fr.Origin, FromUser), Pinned: fr.Pinned, Tags: CleanTags(fr.Tags), + Why: strings.TrimSpace(fr.Why), SupersededBy: fr.SupersededBy, Skill: fr.Skill} + if len(m.Tags) == 0 { + m.Tags = nil + } + var err error + if m.Created, err = unstamp(fr.Created, mod); err != nil { + return nil, err + } + if m.Updated, err = unstamp(fr.Updated, mod); err != nil { + return nil, err + } + if m.Edited, err = unstamp(fr.Edited, time.Time{}); err != nil { + return nil, err + } + for _, src := range fr.Sources { + at, err := unstamp(src.At, time.Time{}) + if err != nil { + return nil, err + } + m.Sources = append(m.Sources, Source{Agent: src.Agent, Session: src.Session, Dir: src.Dir, File: src.File, Quote: src.Quote, At: at}) + } + if err := check(m); err != nil { + return nil, err + } + return m, nil +} + +func cmpOr(s, or string) string { + if s = strings.TrimSpace(s); s != "" { + return strings.ToLower(s) + } + return or +} + +// validID is an id that can name a file in Dir: one from another computer +// that can't is never written. +func validID(id string) bool { + return id != "" && len(id) <= 100 && !strings.HasPrefix(id, ".") && !strings.ContainsAny(id, `/\:*?"<>|`) && + !strings.ContainsFunc(id, func(r rune) bool { return r < ' ' }) +} + +func hashOf(b []byte) string { + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} + +// entry is one file in index.json. +type entry struct { + Size int64 `json:"size"` + Mod time.Time `json:"mod"` + Hash string `json:"hash"` + Memory *Memory `json:"memory"` +} + +type index struct { + Version int `json:"version"` + Files map[string]*entry `json:"files"` +} + +// loadIndex is index.json, empty when it isn't there or can't be read: it +// is only a cache. +func loadIndex() *index { + x := &index{} + if b, err := os.ReadFile(in(indexName)); err == nil { + json.Unmarshal(b, x) + } + if x.Version != 1 || x.Files == nil { + x = &index{Version: 1, Files: map[string]*entry{}} + } + return x +} + +// noted are the memory files read as broken, by name and hash, so each is +// logged once. +var noted sync.Map + +// read reads memory from Dir, under mu: a change a journal holds is +// finished first, memory.json moved in when Dir has none yet. A memory +// file that can't be read is unknown: left out, and never written over +// nor removed (f.broken). meta.json that can't be read is an error. +func read() (*file, error) { + if err := replay(); err != nil { + return nil, err + } + f := &file{Version: 1, seen: map[string]string{}, broken: map[string]bool{}, written: map[string]string{}} + var mt meta + b, err := lastgood.Read(in(metaName), lastgood.Into[meta]) + switch { + case errors.Is(err, fs.ErrNotExist): + if _, err := os.Stat(Path()); !errors.Is(err, fs.ErrNotExist) { + return migrate() + } + case err != nil: + return nil, err + default: + if err := json.Unmarshal(b, &mt); err != nil { + return nil, err + } + f.metaB = b + f.Projects, f.Digest, f.Published, f.Dismissed, f.Removed, f.Declined = mt.Projects, mt.Digest, mt.Published, mt.Dismissed, mt.Removed, mt.Declined + if mt.Written != nil { + f.written = mt.Written + } + } + es, err := os.ReadDir(Dir()) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, err + } + x := loadIndex() + dirty := false + names := map[string]bool{} + for _, e := range es { + name := e.Name() + id, ok := strings.CutSuffix(name, ".md") + if e.IsDir() || !ok || !validID(id) { + continue + } + info, err := e.Info() + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + f.broken[id] = true + continue + } + names[name] = true + var m *Memory + var h string + if en := x.Files[name]; en != nil && en.Memory != nil && en.Size == info.Size() && en.Mod.Equal(info.ModTime()) { + c := *en.Memory + m, h = &c, en.Hash + } else { + data, err := os.ReadFile(filepath.Join(Dir(), name)) + if errors.Is(err, fs.ErrNotExist) { + continue + } + if err != nil { + f.broken[id] = true + continue + } + h = hashOf(data) + if m, err = decode(id, data, info.ModTime()); err != nil { + f.broken[id], f.seen[id] = true, h + if _, was := noted.LoadOrStore(name+h, true); !was { + log.Printf("memory: %s can't be read, left as it is: %v", name, err) + } + delete(x.Files, name) + continue + } + x.Files[name] = &entry{Size: info.Size(), Mod: info.ModTime(), Hash: h, Memory: m} + c := *m + m = &c + dirty = true + } + f.seen[id] = h + if f.metaB != nil && f.written[id] != h { + // changed, or added, by hand: the user's + t := info.ModTime() + if t.Before(m.Updated) { + t = m.Updated + } + m.Origin, m.Updated, m.Edited = FromUser, t, t + } + if u, ok := mt.Used[id]; ok { + m.Used, m.Uses = u.At, u.Uses + } + f.Memories = append(f.Memories, m) + } + for name := range x.Files { + if !names[name] { + delete(x.Files, name) + dirty = true + } + } + if dirty && len(es) > 0 { + if b, err := json.Marshal(x); err == nil { + edit.WriteAtomic(in(indexName), b) // a cache: a failed write costs a parse + } + } + slices.SortFunc(f.Memories, func(a, b *Memory) int { + if c := a.Created.Compare(b.Created); c != 0 { + return c + } + return strings.Compare(a.ID, b.ID) + }) + return f, nil +} + +// op is one file a write puts down (Data) or removes (Del). +type op struct { + Name string `json:"name"` + Data string `json:"data,omitempty"` + Del bool `json:"del,omitempty"` +} + +type journal struct { + Ops []op `json:"ops"` +} + +// write writes what changed in f since read: each memory file whose text +// is new, each removed, and meta.json. Changing more than one, it puts +// every file down in journal.json first. A memory file that changed on +// disk since read (a hand edit made meanwhile) is left as it is: the +// user's edit stays, and the next read takes it. +func write(f *file) error { + written := maps.Clone(f.written) + if written == nil { + written = map[string]string{} + } + mt := meta{Version: 1, Projects: f.Projects, Digest: f.Digest, Published: f.Published, Dismissed: f.Dismissed, + Removed: f.Removed, Declined: f.Declined, Written: written} + var ops []op + kept := map[string]bool{} + for _, m := range f.Memories { + if !validID(m.ID) || f.broken[m.ID] || kept[m.ID] { + continue + } + kept[m.ID] = true + if !m.Used.IsZero() || m.Uses > 0 { + if mt.Used == nil { + mt.Used = map[string]use{} + } + mt.Used[m.ID] = use{At: m.Used, Uses: m.Uses} + } + b, err := encode(m) + if err != nil { + return err + } + h := hashOf(b) + if h == f.seen[m.ID] { + written[m.ID] = h + continue + } + if cur, err := os.ReadFile(in(m.ID + ".md")); err == nil && hashOf(cur) != f.seen[m.ID] || + err != nil && !errors.Is(err, fs.ErrNotExist) || err != nil && f.seen[m.ID] != "" { + continue // changed (or gone, or unreadable) since read: not ours to write over + } + ops = append(ops, op{Name: m.ID + ".md", Data: string(b)}) + written[m.ID] = h + } + for _, id := range slices.Sorted(maps.Keys(f.seen)) { + if kept[id] || f.broken[id] { + continue + } + if cur, err := os.ReadFile(in(id + ".md")); err == nil && hashOf(cur) != f.seen[id] || + err != nil && !errors.Is(err, fs.ErrNotExist) { + continue // edited by hand since read: the user's, kept + } + ops = append(ops, op{Name: id + ".md", Del: true}) + } + for id := range written { + if !kept[id] && !f.broken[id] { + delete(written, id) + } + } + if len(written) == 0 { + mt.Written = nil + } + mb, err := json.MarshalIndent(mt, "", " ") + if err != nil { + return err + } + if f.metaB == nil || !bytes.Equal(mb, f.metaB) { + ops = append(ops, op{Name: metaName, Data: string(mb)}) + } + if len(ops) == 0 { + return nil + } + if err := os.MkdirAll(Dir(), 0o700); err != nil { + return err + } + if len(ops) > 1 { + jb, err := json.Marshal(journal{Ops: ops}) + if err != nil { + return err + } + if err := edit.WriteAtomic(in(journalName), jb); err != nil { + return err + } + } + if err := putDown(ops); err != nil { + return err // the journal stays: the next read finishes it + } + if len(ops) > 1 { + return os.Remove(in(journalName)) + } + return nil +} + +// putDown puts ops down, each file whole (written through a temp file). +func putDown(ops []op) error { + for _, o := range ops { + id, md := strings.CutSuffix(o.Name, ".md") + if !(md && validID(id) || o.Name == metaName) { + return fmt.Errorf("memory: the journal names %q, not a memory file", o.Name) + } + p := in(o.Name) + if o.Del { + if err := os.Remove(p); err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + continue + } + if o.Name == metaName { + if err := lastgood.Keep(p, lastgood.Into[meta], 0o600); err != nil { + return err + } + } + if err := edit.WriteAtomic(p, []byte(o.Data)); err != nil { + return err + } + if err := cut(); err != nil { + return err + } + } + return nil +} + +// cut is called after each file putDown writes; a test's makes a write +// stop there, as a crash would. +var cut = func() error { return nil } + +// replay finishes the change a journal holds, if one was cut off. A +// journal that can't be read is an error: what was written of it is +// unknown. +func replay() error { + b, err := os.ReadFile(in(journalName)) + if errors.Is(err, fs.ErrNotExist) { + return nil + } + if err != nil { + return err + } + var j journal + if err := json.Unmarshal(b, &j); err != nil { + return fmt.Errorf("memory: %s can't be read: %w", in(journalName), err) + } + if err := putDown(j.Ops); err != nil { + return err + } + return os.Remove(in(journalName)) +} + +// migrate moves memory.json into Dir, all at once (a journal), keeps it as +// memory.json.migrated, and reads Dir. A memory.json that can't be read +// is an error, and nothing is written. +func migrate() (*file, error) { + b, err := lastgood.Read(Path(), lastgood.Into[file]) + if err != nil { + return nil, err + } + old := &file{} + if err := json.Unmarshal(b, old); err != nil { + return nil, err + } + old.Memories = slices.DeleteFunc(old.Memories, func(m *Memory) bool { return m == nil || !validID(m.ID) }) + if err := write(old); err != nil { + return nil, err + } + if err := os.Rename(Path(), Path()+".migrated"); err != nil { + log.Printf("memory: moved into %s, but memory.json stays: %v", Dir(), err) + } + return read() +} + +// change reads memory, lets fn change it and writes what changed, one +// magpie at a time. Memory that can't be read is never written over. +func change(fn func(f *file) error) error { + mu.Lock() + defer mu.Unlock() + f, err := read() + if err != nil { + return err + } + if err := fn(f); err != nil { + return err + } + return write(f) +} + +// view reads memory under the lock: consistent with the last write, and +// with no journal left half done. +func view() (*file, error) { + mu.Lock() + defer mu.Unlock() + return read() +} + +// cached is memory for the digest, which a library sync reads for every +// agent: index.json keeps it to a listing and a stat a file. +func cached() (*file, error) { return view() } + +// Modified is when memory last changed, zero when there is none: for a +// reader to tell whether it changed. +func Modified() time.Time { + var t time.Time + es, _ := os.ReadDir(Dir()) + for _, e := range es { + if e.Name() == indexName { + continue + } + if i, err := e.Info(); err == nil && i.ModTime().After(t) { + t = i.ModTime() + } + } + return t +} + +// scopeOf is a front matter's scope: as written, since a project's holds +// a path, but "global" in any case is Global, and none is Global too. +func scopeOf(s string) string { + if s = strings.TrimSpace(s); s == "" || strings.EqualFold(s, Global) { + return Global + } + return s +} diff --git a/internal/memory/store_test.go b/internal/memory/store_test.go new file mode 100644 index 000000000..6815ae830 --- /dev/null +++ b/internal/memory/store_test.go @@ -0,0 +1,303 @@ +package memory + +import ( + "errors" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +func mdOf(id string) string { return filepath.Join(Dir(), id+".md") } + +func readFile(t *testing.T, p string) string { + t.Helper() + b, err := os.ReadFile(p) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// handWrite writes p as a person's editor would, a second later than +// anything before it. +func handWrite(t *testing.T, p, s string) { + t.Helper() + if err := os.WriteFile(p, []byte(s), 0o600); err != nil { + t.Fatal(err) + } + later := time.Now().Add(time.Second) + if err := os.Chtimes(p, later, later); err != nil { + t.Fatal(err) + } +} + +// Each memory is a Markdown file of its own: its fields as front matter, +// its text as the body, and nothing else is kept in one file of all. +func TestEachMemoryIsAMarkdownFile(t *testing.T) { + fresh(t) + m := save(t, "Releases go out on Tuesdays", Fact, Global, "release") + s := readFile(t, mdOf(m.ID)) + for _, want := range []string{"---\nkind: fact\n", "scope: global\n", "tags: [release]\n", "origin: agent\n", "---\n\nReleases go out on Tuesdays\n"} { + if !strings.Contains(s, want) { + t.Fatalf("%q not in\n%s", want, s) + } + } + if _, err := os.Stat(Path()); !errors.Is(err, fs404) { + t.Fatalf("memory.json written: %v", err) + } + back := get(t, m.ID) + if back.Text != m.Text || !back.Created.Equal(m.Created) || back.Sources[0].Agent != "codex" || back.Origin != FromAgent { + t.Fatalf("read back %+v", back) + } + // a project's scope holds a path, its case kept + p := save(t, "Uses make", Fact, "project:dir:/Users/Me/Proj") + if got := get(t, p.ID); got.Scope != "project:dir:/Users/Me/Proj" { + t.Fatalf("scope read back as %q", got.Scope) + } +} + +var fs404 = os.ErrNotExist + +// memory.json from before is moved into the folder on the first read, all +// of it: memories, how often each was used, projects, dismissed texts, +// deletions and declined suggestions. It is kept as memory.json.migrated, +// and nothing moved reads as the user's hand edit. +func TestMemoryJSONIsMovedIn(t *testing.T) { + fresh(t) + old := `{"version":1,"memories":[ +{"id":"m_a","text":"Uses pnpm","kind":"preference","scope":"global","origin":"inferred","status":"candidate","created":"2026-11-01T10:00:00+08:00","updated":"2026-11-02T10:00:00+08:00","used":"2026-11-03T10:00:00+08:00","uses":4,"sources":[{"agent":"claude","quote":"use pnpm","at":"2026-11-01T10:00:00+08:00"}]}, +{"id":"m_b","text":"Deploys need the VPN","kind":"fact","scope":"project:github.com/x/y","origin":"user","status":"active","pinned":true,"why":"the host is private","created":"2026-11-01T11:00:00Z","updated":"2026-11-01T11:00:00Z","edited":"2026-11-01T11:00:00Z"}], +"projects":{"github.com/x/y":{"key":"github.com/x/y","name":"y","roots":["/w/y"]}}, +"dismissed":["tabs, not spaces"],"removed":{"m_gone":"2026-11-05T00:00:00Z"},"declined":["k1"]}` + if err := os.WriteFile(Path(), []byte(old), 0o600); err != nil { + t.Fatal(err) + } + all, projects, err := All() + if err != nil || len(all) != 2 { + t.Fatalf("%v %v", all, err) + } + a, b := get(t, "m_a"), get(t, "m_b") + if a.Origin != FromInferred || a.Status != Candidate || a.Uses != 4 || a.Used.IsZero() || !a.Edited.IsZero() || len(a.Sources) != 1 { + t.Fatalf("m_a: %+v", a) + } + if !b.Pinned || b.Why != "the host is private" || !b.Edited.Equal(b.Updated) || b.Scope != "project:github.com/x/y" { + t.Fatalf("m_b: %+v", b) + } + if projects["github.com/x/y"] == nil { + t.Fatalf("projects %v", projects) + } + bun, err := Collect() + if err != nil || !slices.Equal(bun.Dismissed, []string{"tabs, not spaces"}) || bun.Removed["m_gone"].IsZero() || !slices.Equal(bun.Declined, []string{"k1"}) { + t.Fatalf("%+v %v", bun, err) + } + if _, err := os.Stat(Path()); !errors.Is(err, fs404) { + t.Fatal("memory.json left in place") + } + if s := readFile(t, Path()+".migrated"); s != old { + t.Fatal("memory.json not kept as it was") + } + if !strings.Contains(readFile(t, mdOf("m_a")), "Uses pnpm") { + t.Fatal("no file for m_a") + } +} + +// A memory file the user edits by hand is their change: theirs (Fixed), +// so a tidy leaves it and a sync of an agent's older change from another +// computer doesn't write over it; and its text is what they wrote. +func TestHandEditIsTheUsers(t *testing.T) { + a, b, at := twoComputers(t) + a.use(t) + m := infer(t, "Uses npm", Global) + carry(t, a, b) + a.use(t) + p := mdOf(m.ID) + handWrite(t, p, strings.Replace(readFile(t, p), "\n\nUses npm\n", "\n\nUses pnpm, never npm\n", 1)) + got := get(t, m.ID) + if got.Text != "Uses pnpm, never npm" || got.Origin != FromUser || !Fixed(got) || !byUser(got) { + t.Fatalf("hand edit read as %+v", got) + } + if cs, err := Tidy(Plan{Stale: []Stale{{ID: m.ID, Why: "old"}}, Before: at.Add(time.Hour)}); err != nil || len(cs) != 0 { + t.Fatalf("tidy changed the user's: %+v %v", cs, err) + } + // on the other computer an agent changes it later than the hand edit + b.use(t) + *at = time.Now().Add(24 * time.Hour) + if _, err := Edit(m.ID, Input{Tags: &[]string{"js"}}, false); err != nil { + t.Fatal(err) + } + carry(t, b, a) + a.use(t) + if got := get(t, m.ID); got.Text != "Uses pnpm, never npm" { + t.Fatalf("an agent's sync wrote over the hand edit: %+v", got) + } + if !strings.Contains(readFile(t, p), "Uses pnpm, never npm") { + t.Fatalf("file: %s", readFile(t, p)) + } +} + +// A file the user adds is a memory of theirs, its name its id; what the +// front matter leaves out is a fact that holds everywhere, in use. +func TestHandAddedFileIsAMemory(t *testing.T) { + fresh(t) + save(t, "something", Fact, Global) // the folder and meta.json are there + handWrite(t, mdOf("vpn"), "Deploys need the VPN\n") + handWrite(t, mdOf("tz"), "---\nkind: preference\ntags: [time]\ncreated: 2026-11-01\n---\nDates in UTC+8\n") + v, z := get(t, "vpn"), get(t, "tz") + if v.Text != "Deploys need the VPN" || v.Kind != Fact || v.Scope != Global || v.Status != Active || v.Origin != FromUser { + t.Fatalf("vpn: %+v", v) + } + if z.Kind != Preference || !slices.Equal(z.Tags, []string{"time"}) || z.Created.Day() != 1 { + t.Fatalf("tz: %+v", z) + } + hits, err := Search(Query{Text: "VPN"}) + if err != nil || len(hits) != 1 || hits[0].ID != "vpn" { + t.Fatalf("search: %+v %v", hits, err) + } +} + +// A memory file that can't be read is unknown: left out, and never +// written over nor removed, whatever changes the rest, a sync included. +func TestBrokenFileIsLeftAsItIs(t *testing.T) { + fresh(t) + m := save(t, "kept", Fact, Global) + bad := "---\nkind: [fact\n---\nhalf typed" + handWrite(t, mdOf(m.ID), bad) + all, _, err := All() + if err != nil || len(all) != 0 { + t.Fatalf("%v %v", all, err) + } + save(t, "another", Fact, Global) + other := *m + other.Text, other.Updated = "from elsewhere", m.Updated.Add(time.Hour) + if _, err := Put(&Bundle{Memories: []*Memory{&other}}); err != nil { + t.Fatal(err) + } + if err := Remove(m.ID); !errors.Is(err, ErrNotFound) { + t.Fatalf("removed: %v", err) + } + if s := readFile(t, mdOf(m.ID)); s != bad { + t.Fatalf("written over: %q", s) + } + // fixed by hand, it is read again + handWrite(t, mdOf(m.ID), "kept, fixed") + if got := get(t, m.ID); got.Text != "kept, fixed" { + t.Fatalf("%+v", got) + } +} + +// A change to several memories cut off halfway is finished by the next +// read: never left half done. +func TestCutOffChangeIsFinished(t *testing.T) { + fresh(t) + a := infer(t, "Ships on Tuesdays", Global) + b := infer(t, "Releases go out every Tuesday", Global) + n := 0 + cut = func() error { + if n++; n == 1 { + return errors.New("crash") + } + return nil + } + _, err := Tidy(Plan{Merges: []Merge{{IDs: []string{a.ID, b.ID}, Text: "Releases ship on Tuesdays"}}}) + cut = func() error { return nil } + if err == nil { + t.Fatal("the cut didn't stop the write") + } + all, _, err := All() + if err != nil { + t.Fatal(err) + } + var merged *Memory + for _, m := range all { + if m.Text == "Releases ship on Tuesdays" { + merged = m + } + } + if merged == nil || get(t, a.ID).SupersededBy != merged.ID || get(t, b.ID).SupersededBy != merged.ID { + t.Fatalf("left half done: %+v", all) + } + if _, err := os.Stat(filepath.Join(Dir(), "journal.json")); !errors.Is(err, fs404) { + t.Fatalf("journal left: %v", err) + } + // and none of it reads as a hand edit + if merged.Origin != FromInferred || get(t, a.ID).Origin != FromInferred { + t.Fatalf("read as the user's: %+v", merged) + } +} + +// A hand edit made while magpie changes the same memory stays: the write +// leaves a file that changed since it was read. +func TestHandEditDuringAChangeStays(t *testing.T) { + fresh(t) + m := save(t, "Uses npm", Fact, Global) + err := change(func(f *file) error { + handWrite(t, mdOf(m.ID), "Uses pnpm") + find(f, m.ID).Tags = []string{"js"} + return nil + }) + if err != nil { + t.Fatal(err) + } + if got := get(t, m.ID); got.Text != "Uses pnpm" || got.Origin != FromUser { + t.Fatalf("%+v", got) + } +} + +// A memory removed while its file is edited by hand stays: the edit is +// the user's, and they kept it. +func TestHandEditDuringARemoveStays(t *testing.T) { + fresh(t) + m := save(t, "Uses npm", Fact, Global) + err := change(func(f *file) error { + handWrite(t, mdOf(m.ID), "Uses pnpm") + f.Memories = nil + return nil + }) + if err != nil { + t.Fatal(err) + } + if got := get(t, m.ID); got.Text != "Uses pnpm" || got.Origin != FromUser { + t.Fatalf("%+v", got) + } +} + +// A search's use is kept in meta.json: the memory's own file isn't +// rewritten for it. +func TestUseDoesNotRewriteTheMemory(t *testing.T) { + at := fresh(t) + m := save(t, "Deploys need the VPN", Fact, Global) + before := readFile(t, mdOf(m.ID)) + *at = at.Add(time.Hour) + if hits, err := Search(Query{Text: "VPN"}); err != nil || len(hits) != 1 { + t.Fatalf("%v %v", hits, err) + } + if got := get(t, m.ID); got.Uses != 1 { + t.Fatalf("use not kept: %+v", got) + } + if readFile(t, mdOf(m.ID)) != before { + t.Fatal("the memory's file was rewritten for a search") + } +} + +// index.json is a cache: gone or garbled, memory reads the same. +func TestIndexIsOnlyACache(t *testing.T) { + fresh(t) + save(t, "one", Fact, Global) + save(t, "two", Fact, Global) + want, _, _ := All() + for _, s := range []string{"", "{garbled"} { + p := filepath.Join(Dir(), "index.json") + if s == "" { + os.Remove(p) + } else { + os.WriteFile(p, []byte(s), 0o600) + } + got, _, err := All() + if err != nil || len(got) != len(want) || got[0].Text != want[0].Text || got[1].Text != want[1].Text { + t.Fatalf("%q: %v %v", s, got, err) + } + } +} diff --git a/internal/memory/sync.go b/internal/memory/sync.go index e35a55709..415f80316 100644 --- a/internal/memory/sync.go +++ b/internal/memory/sync.go @@ -39,11 +39,15 @@ type Bundle struct { Declined []string `json:"declined,omitempty"` } -// Collect is this computer's memory, to carry: nil when memory.json isn't -// there, an error when it is and can't be read (a failed read is unknown: -// a backup of it as nothing would say there was nothing). +// Collect is this computer's memory, to carry: nil when there is none (no +// Dir, no memory.json to move in), an error when it can't be read (a failed read is +// unknown: a backup of it as nothing would say there was nothing). A +// memory whose file can't be read is left out: absent from a bundle is not +// removed (Combine), so no other computer drops it for that. func Collect() (*Bundle, error) { - if _, err := os.Stat(Path()); errors.Is(err, fs.ErrNotExist) { + _, e1 := os.Stat(Path()) + _, e2 := os.Stat(Dir()) + if errors.Is(e1, fs.ErrNotExist) && errors.Is(e2, fs.ErrNotExist) { return nil, nil } f, err := view() @@ -209,8 +213,8 @@ func later(x, y *Memory) bool { return string(jx) > string(jy) } -// Put merges b into memory here (Combine), writing memory.json only when -// that changes it. It reports whether it did; a file here that can't be +// Put merges b into memory here (Combine), writing only when that +// changes it. It reports whether it did; a file here that can't be // read is an error, and nothing is written over it. func Put(b *Bundle) (changed bool, err error) { if b == nil {