From 0a08c370804daff49b9ef5ce0bf981b8a79eb9ba Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 10 Nov 2026 01:29:15 +0800 Subject: [PATCH] memory: Tidy merges and sets aside, Untidy undoes it The store side of the nightly tidy (Dreaming). Tidy takes a plan: merges of memories that say the same thing, memories to set aside, and a date before which unreviewed distilled candidates are set aside. What the user wrote or pinned is never rewritten or set aside; merged with others it is the one kept, word for word, and two of them are never merged. A merge across scopes or of a memory no longer in use isn't done. Each change is returned with the states it replaced, and Untidy puts back only what is still as Tidy left it; a merged memory the user edited since stays. Run: mote-run go test -count=1 ./internal/memory: ok. Broken by hand: dropping the user/pinned guard on stale turns TestTidyNeverChangesTheUsers red; dropping Untidy's "still archived" check turns TestUntidyKeepsWhatTheUserChanged red (undo: 3). --- internal/memory/tidy.go | 198 +++++++++++++++++++++++++++++++++++ internal/memory/tidy_test.go | 167 +++++++++++++++++++++++++++++ 2 files changed, 365 insertions(+) create mode 100644 internal/memory/tidy.go create mode 100644 internal/memory/tidy_test.go diff --git a/internal/memory/tidy.go b/internal/memory/tidy.go new file mode 100644 index 000000000..edfb86752 --- /dev/null +++ b/internal/memory/tidy.go @@ -0,0 +1,198 @@ +package memory + +import ( + "slices" + "strings" + "time" +) + +// Tidying is memory's nightly pass (memdistill's Dream): memories that +// say the same thing are merged into one, ones a newer memory replaced +// or whose time has passed are set aside, and candidates nobody reviewed +// for long are set aside too. What the user wrote and what is pinned is +// never changed: it can be the one others are merged into, nothing more. +// Every change is recorded so the whole pass can be undone (Untidy). + +// Merge is memories to merge: IDs into one that says Text. +type Merge struct { + IDs []string + Text string + Kind string +} + +// Stale is a memory to set aside, and why. +type Stale struct { + ID string + Why string +} + +// Plan is what a tidy does: the merges, the memories to set aside, and +// Before, when an unreviewed candidate distilled from a conversation is +// set aside if it hasn't changed since (zero: none). +type Plan struct { + Merges []Merge + Stale []Stale + Before time.Time +} + +// What a Change did. +const ( + Merged = "merge" // IDs were superseded by Into + SetAside = "aside" // IDs were archived + Unreviewed = "unreviewed" // Why of a candidate set aside for its age +) + +// Change is one thing a tidy did, with what it takes to undo it. +type Change struct { + Action string `json:"action"` + // Into is the memory merged into; New when the merge made it + Into string `json:"into,omitempty"` + New bool `json:"new,omitempty"` + // IDs are the memories superseded or set aside, Was their states + // before + IDs []string `json:"ids"` + Was []string `json:"was"` + // Text is what Into says, or what was set aside + Text string `json:"text"` + Why string `json:"why,omitempty"` +} + +// Fixed is a memory a tidy never changes: the user's own, or pinned. +func Fixed(m *Memory) bool { return m.Pinned || m.Origin == FromUser } + +func live(m *Memory) bool { return m != nil && (m.Status == Active || m.Status == Candidate) } + +// Tidy does p, as far as it still holds: a memory gone, no longer in use +// or the user's own is left alone, and a merge across scopes or of two +// of the user's own isn't done. It returns what it did. +func Tidy(p Plan) ([]Change, error) { + var out []Change + err := change(func(f *file) error { + t := now().UTC() + for _, mg := range p.Merges { + var ms []*Memory + for _, id := range mg.IDs { + m := find(f, id) + if !live(m) || slices.Contains(ms, m) { + continue + } + ms = append(ms, m) + } + if len(ms) < 2 || slices.ContainsFunc(ms, func(m *Memory) bool { return m.Scope != ms[0].Scope }) { + continue + } + var fixed []*Memory + for _, m := range ms { + if Fixed(m) { + fixed = append(fixed, m) + } + } + if len(fixed) > 1 { + continue + } + var into *Memory + c := Change{Action: Merged} + if len(fixed) == 1 { + into = fixed[0] + } else { + text := strings.TrimSpace(mg.Text) + if text == "" || len(text) > MaxText { + continue + } + kind := mg.Kind + if !slices.Contains(Kinds, kind) { + kind = ms[0].Kind + } + into = &Memory{ID: newID(), Text: text, Kind: kind, Scope: ms[0].Scope, Origin: FromInferred, Status: Candidate, Created: ms[0].Created, Updated: t} + for _, m := range ms { + if m.Status == Active { + into.Status = Active + } + if into.Why == "" { + into.Why = m.Why + } + for _, tg := range m.Tags { + if !slices.Contains(into.Tags, tg) { + into.Tags = append(into.Tags, tg) + } + } + into.Sources = append(into.Sources, m.Sources...) + if m.Created.Before(into.Created) { + into.Created = m.Created + } + if m.Used.After(into.Used) { + into.Used = m.Used + } + into.Uses += m.Uses + } + slices.SortStableFunc(into.Sources, func(a, b Source) int { return a.At.Compare(b.At) }) + into.Sources = keepSources(into.Sources) + f.Memories = append(f.Memories, into) + c.New = true + } + c.Into, c.Text = into.ID, into.Text + for _, m := range ms { + if m == into { + continue + } + c.IDs, c.Was = append(c.IDs, m.ID), append(c.Was, m.Status) + m.Status, m.SupersededBy, m.Updated = Superseded, into.ID, t + } + out = append(out, c) + } + aside := func(m *Memory, why string) { + out = append(out, Change{Action: SetAside, IDs: []string{m.ID}, Was: []string{m.Status}, Text: m.Text, Why: why}) + m.Status, m.Updated = Archived, t + } + for _, s := range p.Stale { + if m := find(f, s.ID); live(m) && !Fixed(m) { + aside(m, strings.TrimSpace(s.Why)) + } + } + if !p.Before.IsZero() { + for _, m := range f.Memories { + if m.Status == Candidate && m.Origin == FromInferred && !Fixed(m) && m.Updated.Before(p.Before) { + aside(m, Unreviewed) + } + } + } + if len(out) == 0 { + return errSkip + } + return nil + }) + if err == errSkip { + err = nil + } + return out, err +} + +// Untidy undoes cs: each memory a tidy superseded or set aside, and still +// left so, goes back to the state it had, and a memory a merge made is +// removed, unless the user has made it theirs since (it stays then, with +// the ones it was made from back beside it). It returns how many memories +// came back. +func Untidy(cs []Change) (int, error) { + n := 0 + err := change(func(f *file) error { + t := now().UTC() + for i := len(cs) - 1; i >= 0; i-- { + c := cs[i] + for k, id := range c.IDs { + m := find(f, id) + if m == nil || k >= len(c.Was) { + continue + } + if c.Action == Merged && m.Status == Superseded && m.SupersededBy == c.Into || c.Action == SetAside && m.Status == Archived { + m.Status, m.SupersededBy, m.Updated = c.Was[k], "", t + n++ + } + } + if c.New { + f.Memories = slices.DeleteFunc(f.Memories, func(m *Memory) bool { return m.ID == c.Into && !Fixed(m) }) + } + } + return nil + }) + return n, err +} diff --git a/internal/memory/tidy_test.go b/internal/memory/tidy_test.go new file mode 100644 index 000000000..5e931ce4f --- /dev/null +++ b/internal/memory/tidy_test.go @@ -0,0 +1,167 @@ +package memory + +import ( + "slices" + "testing" + "time" +) + +func infer(t *testing.T, text, scope string, tags ...string) *Memory { + t.Helper() + k, st := Fact, Candidate + m, _, err := Save(Input{Text: &text, Kind: &k, Scope: &scope, Tags: &tags, Status: &st}, FromInferred, &Source{Agent: "claude", Quote: text}, nil) + if err != nil { + t.Fatal(err) + } + return m +} + +func get(t *testing.T, id string) *Memory { + t.Helper() + m, err := Get(id) + if err != nil { + t.Fatalf("%s: %v", id, err) + } + return m +} + +// Two memories that say the same thing become one, which carries both +// one's tags and sources and is in use when either was; the two are kept, +// superseded by it. Undone, the two are back as they were and the merged +// one is gone. +func TestTidyMergesAndUndoes(t *testing.T) { + at := fresh(t) + a := save(t, "Ships on Tuesdays", Fact, Global, "release") + *at = at.Add(time.Hour) + b := infer(t, "Releases go out every Tuesday", Global, "ship") + cs, err := Tidy(Plan{Merges: []Merge{{IDs: []string{b.ID, a.ID}, Text: "Releases ship on Tuesdays", Kind: "nonsense"}}}) + if err != nil || len(cs) != 1 || !cs[0].New { + t.Fatalf("%+v %v", cs, err) + } + m := get(t, cs[0].Into) + if m.Text != "Releases ship on Tuesdays" || m.Kind != Fact || m.Status != Active || m.Origin != FromInferred || + !slices.Equal(m.Tags, []string{"ship", "release"}) || len(m.Sources) != 2 || !m.Created.Equal(a.Created) { + t.Fatalf("merged: %+v", m) + } + for _, id := range []string{a.ID, b.ID} { + if o := get(t, id); o.Status != Superseded || o.SupersededBy != m.ID { + t.Fatalf("member: %+v", o) + } + } + if n, err := Untidy(cs); err != nil || n != 2 { + t.Fatalf("undo: %d %v", n, err) + } + if get(t, a.ID).Status != Active || get(t, b.ID).Status != Candidate || get(t, a.ID).SupersededBy != "" { + t.Fatal("not back as they were") + } + if _, err := Get(m.ID); err != ErrNotFound { + t.Fatalf("merged one left: %v", err) + } +} + +// What the user wrote or pinned is never rewritten or set aside: merged +// with others it is the one kept, word for word; two of them aren't +// merged; and named stale, it stays. +func TestTidyNeverChangesTheUsers(t *testing.T) { + fresh(t) + u, _, err := Save(Input{Text: str("Use tabs"), Kind: str(Preference), Scope: str(Global)}, FromUser, nil, nil) + if err != nil { + t.Fatal(err) + } + p := infer(t, "Pinned one", Global) + pin := true + if _, err := Edit(p.ID, Input{Pinned: &pin}, false); err != nil { + t.Fatal(err) + } + x := infer(t, "Indents with tabs", Global) + y := infer(t, "Old fact", Global) + cs, err := Tidy(Plan{ + Merges: []Merge{{IDs: []string{x.ID, u.ID}, Text: "Rewritten"}, {IDs: []string{u.ID, p.ID}, Text: "Both"}}, + Stale: []Stale{{ID: u.ID}, {ID: p.ID}, {ID: y.ID, Why: "done"}}, + }) + if err != nil || len(cs) != 2 { + t.Fatalf("%+v %v", cs, err) + } + if c := cs[0]; c.New || c.Into != u.ID || !slices.Equal(c.IDs, []string{x.ID}) { + t.Fatalf("merge: %+v", c) + } + if m := get(t, u.ID); m.Text != "Use tabs" || m.Status != Active { + t.Fatalf("user's: %+v", m) + } + if get(t, p.ID).Status != Candidate || get(t, x.ID).SupersededBy != u.ID || get(t, y.ID).Status != Archived { + t.Fatal("wrong ones changed") + } + if n, _ := Untidy(cs); n != 2 || get(t, x.ID).Status != Candidate || get(t, y.ID).Status != Candidate { + t.Fatalf("undo brought back %d", n) + } + if _, err := Get(u.ID); err != nil { + t.Fatal("undo removed the user's memory it was merged into") + } +} + +// A merge across scopes, or of memories gone or out of use, isn't done. +func TestTidySkipsWhatNoLongerHolds(t *testing.T) { + fresh(t) + a := infer(t, "One", Global) + b := infer(t, "Two", "project:github.com/a/b") + c := infer(t, "Three", Global) + if _, err := Forget(c.ID); err != nil { + t.Fatal(err) + } + cs, err := Tidy(Plan{Merges: []Merge{ + {IDs: []string{a.ID, b.ID}, Text: "x"}, + {IDs: []string{a.ID, c.ID}, Text: "x"}, + {IDs: []string{a.ID, "m_gone"}, Text: "x"}, + {IDs: []string{a.ID, a.ID}, Text: "x"}, + }, Stale: []Stale{{ID: c.ID}}}) + if err != nil || len(cs) != 0 { + t.Fatalf("%+v %v", cs, err) + } +} + +// A candidate distilled from a conversation and left unreviewed past +// Before is set aside; a newer one, or one an agent saved, stays. +func TestTidySetsAsideUnreviewed(t *testing.T) { + at := fresh(t) + old := infer(t, "Old candidate", Global) + agent := save(t, "Agent's", Fact, Global) + *at = at.Add(40 * 24 * time.Hour) + nw := infer(t, "New candidate", Global) + cs, err := Tidy(Plan{Before: at.Add(-30 * 24 * time.Hour)}) + if err != nil || len(cs) != 1 || cs[0].IDs[0] != old.ID || cs[0].Why != Unreviewed { + t.Fatalf("%+v %v", cs, err) + } + if get(t, old.ID).Status != Archived || get(t, nw.ID).Status != Candidate || get(t, agent.ID).Status != Active { + t.Fatal("wrong ones set aside") + } +} + +// Undo leaves alone what the user changed since: a memory they brought +// back or archived themselves stays as they left it, and a merged one +// they edited stays theirs. +func TestUntidyKeepsWhatTheUserChanged(t *testing.T) { + fresh(t) + a := infer(t, "A one", Global) + b := infer(t, "A two", Global) + c := infer(t, "Stale", Global) + cs, err := Tidy(Plan{Merges: []Merge{{IDs: []string{a.ID, b.ID}, Text: "A"}}, Stale: []Stale{{ID: c.ID}}}) + if err != nil || len(cs) != 2 { + t.Fatalf("%+v %v", cs, err) + } + if _, err := Edit(cs[0].Into, Input{Text: str("A, as I put it")}, true); err != nil { + t.Fatal(err) + } + act := Active + if _, err := Edit(c.ID, Input{Status: &act}, true); err != nil { + t.Fatal(err) + } + if n, err := Untidy(cs); err != nil || n != 2 { + t.Fatalf("undo: %d %v", n, err) + } + if m := get(t, cs[0].Into); m.Text != "A, as I put it" { + t.Fatalf("edited merge: %+v", m) + } + if get(t, c.ID).Status != Active { + t.Fatal("the user's own change undone") + } +}