library: the agents ticked for instructions are given memory's digest

The agents ticked under Library → Instructions get a "## Memory" part in
their instructions: the global memories, the agent's own, and each
project's under the folders it was seen in (memory.Digest), unless
Instructions.NoMemory. The digest changes only when published, so an
agent's instructions (and the prompt cache on them) change mid-session
only then: at once when the user changes memory (PublishMemory(false),
called by the GUI), and once a day from KeepLinked's loop for what
agents saved meanwhile (PublishMemory(true) -> memory.PublishDue).
PublishDue writes nothing while memory has never held anything, so a
user who never uses memory gets no memory.json.

Run (mote-run, whole worktree, with the rest of the memory layer):
- go test ./internal/memory ./internal/library: ok (library 130.9s)
- go vet ./internal/memory ./internal/library ./internal/gui, GOOS
  darwin, linux, windows: ok
- gofmt -l: clean
Broken by hand (mote-run -run TestMemoryDigestInInstructions):
- memoryDigest's NoMemory check removed: red. It first stayed green,
  since the test switched NoMemory on with memory.json deleted; the test
  now gives memory back and sees the part return before switching it off.
- PublishDue's "nothing kept" guard removed: red ("a due publish with
  nothing kept wrote memory.json").
Not tried: a real agent reading the digest in its instructions.
This commit is contained in:
yetone
2026-11-10 03:25:44 +08:00
parent 4f0c587306
commit 79decfe71a
4 changed files with 198 additions and 6 deletions
+99 -4
View File
@@ -17,6 +17,7 @@ import (
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/memory"
)
// The part of an agent's instructions file magpie writes sits between
@@ -144,14 +145,15 @@ func writeText(path, text string) error {
return edit.WriteAtomic(path, []byte(text+"\n"))
}
// wanted is what magpie writes into the agent's file: the shared text and
// the agent's own additions after it; "" for nothing.
// wanted is what magpie writes into the agent's file: the shared text,
// the agent's own additions after it, and memory's published digest for
// it last; "" for nothing.
func (l *Library) wanted(agent string) string {
if !slices.Contains(l.Instructions.Agents, agent) {
return ""
}
parts := []string{}
for _, s := range []string{setText(l.sharedPath()), readText(extraPath(agent))} {
for _, s := range []string{setText(l.sharedPath()), readText(extraPath(agent)), l.memoryDigest(agent)} {
if s != "" {
parts = append(parts, s)
}
@@ -159,6 +161,84 @@ func (l *Library) wanted(agent string) string {
return strings.Join(parts, "\n\n")
}
// memoryDigest is memory's published digest for the agent, "" when
// NoMemory, or memory.json can't be read (syncInstructions writes nothing
// then: unknown, not empty).
func (l *Library) memoryDigest(id string) string {
if l.Instructions.NoMemory {
return ""
}
d, _ := memory.Digest(memoryAgent(id))
return d
}
// memoryAgent is the agent an agent's memories are kept under: its id
// without where it runs (claude@wsl:Ubuntu is claude), as the gateway
// names the agents that save them.
func memoryAgent(id string) string {
a, _, _ := strings.Cut(id, "@")
return a
}
// PublishMemory makes what memory holds now the digest the agents are
// given (memory.Publish) and, when it changed, writes the instructions
// into them again: a change the user made to memory. due publishes only
// when the last was a day ago (memory.PublishDue), for what agents saved
// meanwhile. nil, nil when nothing changed.
func PublishMemory(due bool) (*Result, error) {
publish := memory.Publish
if due {
publish = memory.PublishDue
}
changed, err := publish()
if err != nil || !changed {
return nil, err
}
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return nil, err
}
res := &Result{Changed: []string{}, Problems: []Problem{}}
if len(l.Instructions.Agents) == 0 || l.Instructions.NoMemory {
return res, nil
}
b := l.kept
if b == nil {
b = newBackups()
}
for _, t := range Targets() {
l.syncInstructions(t, b, res, true)
}
res.Backup = b.dir
if b.dir != "" {
pruneBackups()
}
return res, l.save()
}
// MemoryInInstructions is whether the agents ticked for instructions are
// given memory's digest, and those agents.
func MemoryInInstructions() (bool, []string, error) {
mu.Lock()
defer mu.Unlock()
l, err := load()
if err != nil {
return false, nil, err
}
return !l.Instructions.NoMemory, append([]string{}, l.Instructions.Agents...), nil
}
// SetMemoryInInstructions gives the agents ticked for instructions
// memory's digest, or takes it out of them, at once.
func SetMemoryInInstructions(on bool) (*Result, error) {
return changeInstructions(func(l *Library) error {
l.Instructions.NoMemory = !on
return nil
})
}
// split takes a file apart: what is before magpie's part, magpie's part,
// and what is after it. ok is false when magpie has no part in it.
func split(file string) (before, block, after string, ok bool) {
@@ -271,6 +351,12 @@ func (l *Library) syncInstructions(t *Target, b *backups, res *Result, auto bool
return
}
}
if !l.Instructions.NoMemory {
if _, err := memory.Digest(memoryAgent(id)); err != nil {
res.fail(id, "instructions", fmt.Errorf("memory: %w", err))
return
}
}
}
want := l.wanted(id)
raw, err := edit.Read(t.Instructions)
@@ -753,7 +839,8 @@ func SyncLinked() (*Result, error) {
return changeInstructions(func(*Library) error { return nil })
}
// KeepLinked runs SyncLinked, and Woken, every interval, until ctx ends:
// KeepLinked runs SyncLinked, Woken and a due PublishMemory every
// interval, until ctx ends:
// the app's backend, which ends once it has handed the gateway to the
// new version (gui/handover.go). Before, it ran for as long as the
// process did, and the copy an update left finishing its requests went
@@ -771,6 +858,14 @@ func KeepLinked(ctx context.Context, interval time.Duration) {
}
// what was ticked for a stopped WSL distro's agents, once it runs
keepWoken()
// once a day, what agents saved to memory meanwhile
if res, err := PublishMemory(true); err != nil {
log.Println("library: memory:", err)
} else if res != nil {
for _, p := range res.Problems {
log.Println("library: memory:", p.Agent, p.What, p.Error)
}
}
select {
case <-ctx.Done():
case <-t.C:
+3
View File
@@ -107,6 +107,9 @@ type Instructions struct {
// there is the one magpie always had, "default"
Sets []InstrSet `json:"sets,omitempty"`
Active string `json:"active,omitempty"` // the set agents get; "" is "default"
// NoMemory leaves memory's digest (memory.Digest) out of what the
// agents are written; by default it follows the shared text
NoMemory bool `json:"noMemory,omitempty"`
}
// InstrSet is one set of shared instructions: its text is in its own file.
+92
View File
@@ -0,0 +1,92 @@
package library
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/memory"
)
func memSave(t *testing.T, text, kind, scope string) {
t.Helper()
if _, _, err := memory.Save(memory.Input{Text: &text, Kind: &kind, Scope: &scope}, memory.FromUser, nil, nil); err != nil {
t.Fatal(err)
}
}
// 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
// that can't be read leaves the part as it was (unknown, not empty).
// NoMemory leaves the digest out.
func TestMemoryDigestInInstructions(t *testing.T) {
h := sandbox(t)
shared := "Be brief."
ok(t)(SaveInstructions(InstructionsChange{Shared: &shared, Agents: []string{"codex"}}))
codex := filepath.Join(h, ".codex/AGENTS.md")
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")
}
memSave(t, "Answer in Chinese.", memory.Preference, memory.Global)
memSave(t, "Codex runs tests on mote.", memory.Rule, "agent:codex")
memSave(t, "Claude keeps notes short.", memory.Rule, "agent:claude")
if s := read(t, codex); strings.Contains(s, "Answer in Chinese.") {
t.Fatalf("written before it was published:\n%s", s)
}
ok(t)(PublishMemory(false))
s := read(t, codex)
if !strings.Contains(s, "Be brief.") || !strings.Contains(s, "Answer in Chinese.") || !strings.Contains(s, "Codex runs tests on mote.") || strings.Contains(s, "Claude keeps notes") {
t.Fatalf("codex's instructions:\n%s", s)
}
if strings.Index(s, "Be brief.") > strings.Index(s, "Answer in Chinese.") {
t.Errorf("the digest before the shared text:\n%s", s)
}
if c := filepath.Join(h, ".claude/CLAUDE.md"); strings.Contains(readMaybe(c), "Answer in Chinese.") {
t.Errorf("claude isn't ticked, but was given memory:\n%s", readMaybe(c))
}
// memory.json 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 {
t.Fatal(err)
}
os.Remove(memory.Path() + ".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)
}
if len(res.Problems) == 0 {
t.Errorf("an unreadable memory.json wasn't said: %+v", res)
}
if err := os.Remove(memory.Path()); err != nil {
t.Fatal(err)
}
// readable again: the part is back, then NoMemory takes it out
memSave(t, "Answer in Chinese.", memory.Preference, memory.Global)
ok(t)(PublishMemory(false))
if got := read(t, codex); !strings.Contains(got, "## Memory") {
t.Fatalf("memory readable again, but no digest:\n%s", got)
}
ok(t)(changeInstructions(func(l *Library) error { l.Instructions.NoMemory = true; return nil }))
if got := read(t, codex); !strings.Contains(got, "Be brief.") || strings.Contains(got, "## Memory") {
t.Fatalf("NoMemory:\n%s", got)
}
}
func readMaybe(p string) string {
b, _ := os.ReadFile(p)
return string(b)
}
+4 -2
View File
@@ -130,13 +130,15 @@ func Publish() (changed bool, err error) {
}
// PublishDue publishes when the digest was last published more than a day
// ago and memory changed since. It reports whether any digest changed.
// 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 {
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()