Files
magpie/internal/memory/digest.go
T
yetone a18ed4995f memory: a memory of several lines keeps them, folded to its first line (_meouwu on X)
_meouwu on X: a memory added by hand in several lines showed as one line
with its breaks gone; it should keep its format and, folded, show the
first line and an ellipsis.

Cause: the store never lost the breaks. A memory file's body is
m.Text as written (encode/apply trim only the ends). They were lost
where it was shown: the Library row clamped the name to two lines with
white-space normal, the digest given to agents went through oneLine
(strings.Fields), and so did memory_search / memory_list in the memory
MCP.

Now:
- Library: a folded row and a suggestion show firstLine(text) (first
  line, " …" when more follow); an open row shows the whole text
  pre-wrap. The editor already kept "\n".
- Digest and memory MCP: memory.Indented keeps each line, the lines
  after the first indented two spaces so the memory stays one list
  item.
- Dream and distill listings stay one line on purpose: the model's
  reply is read line by line, and a user's memory is Fixed, never
  rewritten by them. Written in docs/subsystems/memory.md.

Memories saved before: their files already hold the breaks, so after
updating they show, edit and reach agents in their own lines. Nothing
to redo, no migration.

Run at 3fabaf8f2 (on origin/main b332ef7ef, the pushed head),
f6452d777 (on 1622484a8) and ee84e288a (on 54117164c), on the WSL VM magpie-desktop: mote and mica were over
their cores with other sessions' suites for ~2h.
- go vet -tags gtk3 ./... ok; gofmt -l clean.
- go test -tags gtk3 -count=1 -timeout 45m ./... at ee84e288a: 101 ok,
  2 FAIL, both red at origin/main 2416beed6 on the same VM:
  internal/gui TestClipboardReadBack (#7074, #7073), internal/usage
  TestRequestStateKeptAcrossACatalogFetchedAgain (#6572).
- Whole GUI suite (concurrency 8): 1355 of 29368 red in 221 files under
  load. Those 221 again at concurrency 3: 71 red; 66 of them red at
  base 54117164c too. Of the other 5, 3 pass alone;
  codex-auto-reset-settings (#6108) and copilot-ghe (#1949) are red at
  base alone too (2 of 3 and 3 of 3 rounds), commented there.
- After the rebase (f6452d777): internal/memory, internal/memdistill
  and -run "Memory|Budget|I18n" in gateway, gui, library ok. All 84
  library-*.test.cjs: 1920 of 1950 pass; each red file alone, beside
  1622484a8: commands-import, group-steady, mcp-copy-config,
  mcp-off-fold, open-again and all are red at base too (#7097; all 3 of
  3 at base); memory-suggest, mcp-json and bili pass alone.
- At 3fabaf8f2 (b332ef7ef brought flying_crp's digest header and
  memory_save note; conflicts were only both sides adding tests and
  doc text): go vet memory, gateway, memdistill; go test memory,
  memdistill, access, and -run "Memory|Budget|I18n|Digest" in gateway,
  gui, library ok; library-memory*.test.cjs 112 of 112.
- library-memory-lines.test.cjs: 5 langs x 980/420 x chromium/webkit.

Broken by hand (old code, new tests): TestMultiLineMemoryKeepsItsLines
red at the digest step only (save, edit and the file passed: the store
kept the breaks), TestIndented and TestMemorySearchKeepsTheLines red,
library-memory-lines red ("Release steps: …" expected).

Not tried: a macOS run (mote, mica busy), Windows, the real app.
2026-11-19 06:32:40 +08:00

230 lines
6.6 KiB
Go

package memory
import (
"maps"
"slices"
"strings"
"time"
"unicode/utf8"
)
// The digest is the part of memory an agent is given in its instructions,
// so it knows the user's preferences and rules from its first word, before
// it thinks to search. It is held to a budget, pinned memories and the
// kinds that hold longest first, and changes only when Publish is called:
// when the user changes memory, and once a day for what agents saved
// meanwhile. An agent's instructions change mid-session only then, so the
// prompt caches built on them aren't thrown away at every save.
//
// Its text goes to every agent's model vendor: it names neither magpie nor
// any vendor, only the memories and how to read them.
// Budgets, in characters, of the global part and of each project's.
var (
globalBudget = 4000
projectBudget = 1500
agentBudget = 1000
allBudget = 8000
)
var kindTitles = map[string]string{
Profile: "About the user",
Preference: "Preferences",
Rule: "Rules",
Reference: "References",
Fact: "Facts",
Procedure: "How things are done",
Episode: "Recent decisions",
}
// render is the digest of one scope's memories within budget characters:
// a heading per kind, an item per memory (its own lines kept), pinned and newer ones first, and
// none cut in the middle. "" when the scope has none.
func render(ms []*Memory, scope string, budget int) string {
pool := []*Memory{}
for _, m := range ms {
if m.Scope == scope && m.Status == Active {
pool = append(pool, m)
}
}
slices.SortStableFunc(pool, func(a, b *Memory) int {
if a.Pinned != b.Pinned {
if a.Pinned {
return -1
}
return 1
}
if d := kindRank(a.Kind) - kindRank(b.Kind); d != 0 {
return d
}
return b.Updated.Compare(a.Updated)
})
// the lines picked within budget, then put back in kind order
picked := map[string][]string{}
used := 0
for _, m := range pool {
line := "- " + Indented(m.Text, " ")
if m.Why != "" {
line += " (why: " + oneLine(m.Why) + ")"
}
n := utf8.RuneCountInString(line) + 1
if used+n > budget {
continue
}
used += n
picked[m.Kind] = append(picked[m.Kind], line)
}
var b strings.Builder
for _, k := range Kinds {
if len(picked[k]) == 0 {
continue
}
if b.Len() > 0 {
b.WriteString("\n")
}
b.WriteString(kindTitles[k] + ":\n")
b.WriteString(strings.Join(picked[k], "\n"))
b.WriteString("\n")
}
return strings.TrimSpace(b.String())
}
func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") }
// Indented is a memory's text with its line breaks kept, each line after
// the first led by pad, so a memory the user wrote in several lines reads
// as they wrote it and stays one item of a list. Spaces closing a line and
// blank lines' pads are left out.
func Indented(s, pad string) string {
lines := strings.Split(strings.TrimSpace(strings.ReplaceAll(s, "\r\n", "\n")), "\n")
for i, l := range lines {
l = strings.TrimRight(l, " \t\r")
if i > 0 && l != "" {
l = pad + l
}
lines[i] = l
}
return strings.Join(lines, "\n")
}
// publish renders every scope's digest into f.
func publish(f *file) {
scopes := map[string]bool{}
for _, m := range f.Memories {
if m.Status == Active {
scopes[m.Scope] = true
}
}
d := map[string]string{}
for s := range scopes {
budget := globalBudget
switch {
case strings.HasPrefix(s, "project:"):
budget = projectBudget
case strings.HasPrefix(s, "agent:"):
budget = agentBudget
}
if t := render(f.Memories, s, budget); t != "" {
d[s] = t
}
}
f.Digest = d
f.Published = now()
}
// Publish makes what memory holds now the digest agents are given. It
// reports whether any digest changed, for the caller to write it into the
// agents' instructions.
func Publish() (changed bool, err error) {
err = change(func(f *file) error {
old := f.Digest
publish(f)
changed = !maps.Equal(old, f.Digest)
return nil
})
return changed, err
}
// PublishDue publishes when the digest was last published more than a day
// ago, and memory holds something or held something then. It reports
// whether any digest changed.
func PublishDue() (bool, error) {
f, err := view()
if err != nil {
return false, err
}
if now().Sub(f.Published) < 24*time.Hour || (len(f.Memories) == 0 && len(f.Digest) == 0) {
// nothing kept yet: no file written for it
return false, nil
}
return Publish()
}
// 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 can't be read (unknown: the
// caller keeps what the agent has).
func Digest(agent string) (string, error) {
f, err := cached()
if err != nil {
return "", err
}
return digestOf(f, agent), nil
}
func digestOf(f *file, agent string) string {
if len(f.Digest) == 0 {
return ""
}
parts := []string{}
used := 0
add := func(s string) bool {
n := utf8.RuneCountInString(s)
if used+n > allBudget {
return false
}
used += n
parts = append(parts, s)
return true
}
if g := f.Digest[Global]; g != "" {
add(g)
}
if a := f.Digest["agent:"+agent]; agent != "" && a != "" {
add("Only for you:\n" + a)
}
// projects, newest change first
latest := map[string]time.Time{}
for _, m := range f.Memories {
if m.Status == Active && strings.HasPrefix(m.Scope, "project:") && m.Updated.After(latest[m.Scope]) {
latest[m.Scope] = m.Updated
}
}
scopes := []string{}
for s := range f.Digest {
if strings.HasPrefix(s, "project:") {
scopes = append(scopes, s)
}
}
slices.SortFunc(scopes, func(a, b string) int {
if c := latest[b].Compare(latest[a]); c != 0 {
return c
}
return strings.Compare(a, b)
})
for _, s := range scopes {
key := strings.TrimPrefix(s, "project:")
where := key
if p := f.Projects[key]; p != nil && len(p.Roots) > 0 {
where = strings.Join(p.Roots, ", ")
}
add("When working in " + where + ":\n" + f.Digest[s])
}
if len(parts) == 0 {
return ""
}
return "## Memory\n\nWhat is known from earlier conversations with the user. Follow it unless the user says otherwise now. The project's own instruction files (AGENTS.md and the like) and docs come first: where a memory disagrees with them, follow the project's files and tell the user which memory is out of date. A rule or fact of one project belongs in that project's files; memory keeps what holds for the user across projects. When a memory_search tool is at hand, search it for more before asking the user again, and save what they ask to be remembered with memory_save.\n\n" +
strings.Join(parts, "\n\n")
}