diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index 5ea357aca..27fdd0f88 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -125,6 +125,15 @@ one Settings lists, are turned away (`TestMemoryMCPGuarded`). the project, and how each was found, as text and `structuredContent` (`TestMemoryMCPProjectArgumentAndContext`). - A save through MCP is active at once, origin `agent`. +- A project's rules go to the project's files: `memory_save`'s description + says a project's rule, convention or fact belongs in its instruction + files or docs when it keeps them, and a new save of the caller's project + (any kind but profile and preference), or a global rule or procedure, + made where the project's root holds one of `projectInstructionFiles` + (AGENTS.md, CLAUDE.md, GEMINI.md, .github/copilot-instructions.md, + .cursorrules) ends with a note naming the files found and asking the + agent to offer to write it there (`projectFilesNote`, + `TestMemorySavePointsProjectRulesToItsFiles`). The save itself is kept. ### Other memory services @@ -147,7 +156,11 @@ after adding. digest per scope within a budget (global 4000, project 1500, agent 1000, the whole 8000 characters), pinned and longer-lived kinds first, no memory cut in the middle. The text goes to every agent's vendor: it names neither -magpie nor any vendor. +magpie nor any vendor. Its header puts the project's own instruction files +(AGENTS.md and the like) and docs first: where a memory disagrees with +them the agent follows the files and says which memory is out of date, and +a project's rule or fact belongs in its files, memory keeping what holds +across projects (flying_crp on X, `TestDigestDefersToTheProjectsFiles`). The digest changes only when published, so an agent's instructions — and the prompt cache built on them — change mid-session only then @@ -229,7 +242,9 @@ further (`State.Since`), unless a range is picked. tools, no reasoning), cut to 24k characters keeping the head and the tail, plus the memories already kept for that project, under neutral instructions that name neither magpie nor the vendor - (`TestWhatIsSent`, `TestLongConversationCut`). + (`TestWhatIsSent`, `TestLongConversationCut`). They leave a project's + rules and conventions to its own instruction files and docs, and drop + what disagrees with them. - The request goes through the gateway this process serves (`distillComplete`), as `x-api-key: magpie-memory`, so it is routed, masked and counted in Usage under the agent `memory` diff --git a/internal/gateway/memory_mcp.go b/internal/gateway/memory_mcp.go index 52d14f7b7..c80d60e9a 100644 --- a/internal/gateway/memory_mcp.go +++ b/internal/gateway/memory_mcp.go @@ -106,7 +106,9 @@ func memoryMCPTools() []any { "name": memorySaveTool, "title": "Save memory", "description": "Remembers one thing for later conversations, in every agent: what the user asks you to remember, a preference or rule they state, a correction they make, a fact about them or the project that will still hold next time. " + - "One fact per memory, written so it reads on its own. Don't save what is in the code or its history, a task's progress, or secrets. Saving what is already remembered merges into it; with id, changes that memory.", + "One fact per memory, written so it reads on its own. Don't save what is in the code or its history, a task's progress, or secrets. " + + "Memory is for what holds for the user across projects. A rule, convention or fact of one project belongs in that project's own instruction files or docs (AGENTS.md and the like) when it keeps them: offer to write it there instead, and don't save what they already say or what disagrees with them. " + + "Saving what is already remembered merges into it; with id, changes that memory.", "inputSchema": map[string]any{ "type": "object", "properties": map[string]any{ @@ -662,7 +664,49 @@ func memorySave(c memoryCaller, a memoryArgs) (string, error) { if !added { return "Already remembered, merged: " + memoryLine(m, c), nil } - return "Remembered: " + memoryLine(m, c), nil + return "Remembered: " + memoryLine(m, c) + projectFilesNote(c, m), nil +} + +// projectInstructionFiles are the files, under a project's root, an agent +// reads the project's own instructions from. +var projectInstructionFiles = []string{"AGENTS.md", "CLAUDE.md", "GEMINI.md", ".github/copilot-instructions.md", ".cursorrules"} + +// projectFilesNote points a save that belongs in the project's own +// instruction files there: a project's rules kept in memory too disagree +// with those files once the files are tidied (flying_crp on X). It is for +// a memory of the caller's project, or a rule or procedure kept for +// everyone, saved in a project that keeps such files; "" otherwise. It +// names only the files found, never this app nor a vendor. +func projectFilesNote(c memoryCaller, m *memory.Memory) string { + if c.project == nil || m == nil { + return "" + } + inProject := m.Scope == memory.ScopeOf(c.project) + switch { + case inProject && m.Kind != memory.Profile && m.Kind != memory.Preference: + case m.Scope == memory.Global && (m.Kind == memory.Rule || m.Kind == memory.Procedure): + default: + return "" + } + var found []string + for _, root := range c.project.Roots { + for _, f := range projectInstructionFiles { + if fi, err := os.Stat(filepath.Join(root, filepath.FromSlash(f))); err == nil && !fi.IsDir() { + found = append(found, f) + } + } + if len(found) > 0 { + break + } + } + if len(found) == 0 { + return "" + } + files := strings.Join(found, ", ") + if inProject { + return "\nThis project keeps its own instructions in " + files + ". A rule or fact of the project is better written there, where everyone working on it reads it and it is kept up to date with the project: offer the user to add it there, and forget this memory once it is." + } + return "\nIf this holds only in this project, it belongs in the project's own " + files + " rather than in memory: offer the user to add it there, and forget this memory once it is." } func memoryForget(a memoryArgs) (string, error) { diff --git a/internal/gateway/memory_mcp_test.go b/internal/gateway/memory_mcp_test.go index 002c458da..dbbf8d9dc 100644 --- a/internal/gateway/memory_mcp_test.go +++ b/internal/gateway/memory_mcp_test.go @@ -485,3 +485,68 @@ func TestMemoryMCPProjectArgumentAndContext(t *testing.T) { t.Fatalf("tools: %s", w.Body.String()) } } + +// A rule of a project that keeps its own instruction files is pointed +// there when saved, so memory and the project's files don't drift apart +// (flying_crp on X): a project memory, and a rule kept for everyone that +// may hold here alone. A preference, and a project with no such file, +// get no note. The save tool's description says the same, and neither +// names this app nor a vendor. +func TestMemorySavePointsProjectRulesToItsFiles(t *testing.T) { + fresh(t) + h := lanGuard(New().Handler()) + d := t.TempDir() + kept := gitRepo(t, filepath.Join(d, "kept"), "https://github.com/someone/kept.git") + if err := os.WriteFile(filepath.Join(kept, "AGENTS.md"), []byte("# Notes\n"), 0o644); err != nil { + t.Fatal(err) + } + bare := gitRepo(t, filepath.Join(d, "bare"), "https://github.com/someone/bare.git") + in := func(dir string) []string { + return []string{MemoryClientHeader, "codex-mcp-client", MemoryCwdHeader, dir} + } + note := "This project keeps its own instructions in AGENTS.md" + said, bad := memPost(t, h, memorySaveTool, `{"text":"Run tests with -race","kind":"rule","scope":"project"}`, in(filepath.Join(kept, "src"))...) + if bad || !strings.HasPrefix(said, "Remembered") || !strings.Contains(said, note) { + t.Fatalf("a project rule where AGENTS.md is: %s", said) + } + said, _ = memPost(t, h, memorySaveTool, `{"text":"Releases go out on Tuesdays","kind":"fact"}`, in(kept)...) + if !strings.Contains(said, note) { + t.Fatalf("a project fact where AGENTS.md is: %s", said) + } + said, _ = memPost(t, h, memorySaveTool, `{"text":"Commit messages in English","kind":"rule"}`, in(kept)...) + if !strings.Contains(said, "everywhere") || !strings.Contains(said, "If this holds only in this project, it belongs in the project's own AGENTS.md") { + t.Fatalf("a rule for everyone saved in a project with AGENTS.md: %s", said) + } + for _, c := range []struct{ args, dir string }{ + {`{"text":"Answer in Chinese","kind":"preference"}`, kept}, + {`{"text":"Run tests with -count=1","kind":"rule","scope":"project"}`, bare}, + {`{"text":"Keep diffs small","kind":"rule"}`, bare}, + } { + if said, _ := memPost(t, h, memorySaveTool, c.args, in(c.dir)...); strings.Contains(said, "instructions in") || strings.Contains(said, "belongs in") { + t.Errorf("%s in %s: %s", c.args, filepath.Base(c.dir), said) + } + } + w := mcpPostTo(h, MemoryMCPPath, "127.0.0.1:50000", `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`, "Accept", "application/json") + var list struct { + Result struct { + Tools []struct{ Name, Description string } + } + } + if err := json.Unmarshal(w.Body.Bytes(), &list); err != nil { + t.Fatal(err) + } + var desc string + for _, tl := range list.Result.Tools { + if tl.Name == memorySaveTool { + desc = tl.Description + } + for _, name := range []string{"magpie", "openai", "anthropic", "codex"} { + if strings.Contains(strings.ToLower(tl.Description), name) { + t.Errorf("%s's description names %s", tl.Name, name) + } + } + } + if !strings.Contains(desc, "belongs in that project's own instruction files or docs") || !strings.Contains(desc, "across projects") { + t.Fatalf("memory_save's description: %s", desc) + } +} diff --git a/internal/memdistill/memdistill.go b/internal/memdistill/memdistill.go index 6f341d21f..9b698cd08 100644 --- a/internal/memdistill/memdistill.go +++ b/internal/memdistill/memdistill.go @@ -531,7 +531,9 @@ Keep only what stays true beyond this conversation and that a later assistant co Each item rests on words the user wrote in this conversation: quote them exactly. Leave out what only the assistant said, such as rules it follows from its own instructions or notes. -Leave out: the task itself and its progress, anything about this conversation alone, code details visible in the repository, secrets (keys, tokens, passwords), and anything already in "Already known". When nothing is worth keeping, answer []. +A rule or convention of one project belongs in the project's own instruction files and docs, which the user keeps up to date, not here: leave it out unless it is about how this user works everywhere. Never keep an item that disagrees with what the project's files say in the conversation. + +Leave out: the task itself and its progress, anything about this conversation alone, code details visible in the repository, what the project's instruction files or docs say, secrets (keys, tokens, passwords), and anything already in "Already known". When nothing is worth keeping, answer []. Answer with a JSON array alone, at most 5 items: [{"text": "one short sentence, in the language the user wrote in", "kind": "preference", "scope": "global or project", "why": "what in the conversation shows it", "quote": "the user's own words that show it, copied exactly, short"}] diff --git a/internal/memdistill/memdistill_test.go b/internal/memdistill/memdistill_test.go index dd46f2cb9..10f32b7fd 100644 --- a/internal/memdistill/memdistill_test.go +++ b/internal/memdistill/memdistill_test.go @@ -205,6 +205,12 @@ func TestWhatIsSent(t *testing.T) { t.Errorf("sent: %q", w) } } + // a project's rules are left to its own files (flying_crp on X) + for _, w := range []string{"A rule or convention of one project belongs in the project's own instruction files and docs", "Never keep an item that disagrees with what the project's files say", "what the project's instruction files or docs say"} { + if !strings.Contains(sys, w) { + t.Errorf("the instructions lack %q", w) + } + } for _, w := range []string{"magpie", "claude", "codex", "openai", "anthropic", "gpt", "gemini"} { if strings.Contains(strings.ToLower(sys+strings.Split(user, "Conversation:")[0]), w) { t.Errorf("names %q", w) diff --git a/internal/memory/digest.go b/internal/memory/digest.go index 57c61130a..d5bba742d 100644 --- a/internal/memory/digest.go +++ b/internal/memory/digest.go @@ -208,6 +208,6 @@ func digestOf(f *file, agent string) string { 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. 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" + + 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") } diff --git a/internal/memory/digest_test.go b/internal/memory/digest_test.go index 7cf4ad7c7..641828078 100644 --- a/internal/memory/digest_test.go +++ b/internal/memory/digest_test.go @@ -88,3 +88,33 @@ func TestDigestPartsAndBudget(t *testing.T) { } } } + +// The digest defers to the project's own instruction files: a memory that +// disagrees with them loses, and a project's rules are pointed to its +// files (flying_crp on X: memory and AGENTS.md said opposite things, and +// a project's rule went into memory). The header names neither this app +// nor a vendor. +func TestDigestDefersToTheProjectsFiles(t *testing.T) { + fresh(t) + save(t, "Answer in Chinese", Preference, Global) + if _, err := Publish(); err != nil { + t.Fatal(err) + } + d, _ := Digest("codex") + head := strings.SplitN(d, "\n\n", 3)[1] + for _, want := range []string{ + "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", + "A rule or fact of one project belongs in that project's files", + "memory keeps what holds for the user across projects", + } { + if !strings.Contains(head, want) { + t.Errorf("the header lacks %q:\n%s", want, head) + } + } + for _, name := range []string{"magpie", "claude", "codex", "openai", "anthropic", "gemini"} { + if strings.Contains(strings.ToLower(head), name) { + t.Errorf("the header names %s", name) + } + } +}