memory: a project's own instruction files win over memory, and its rules go there (flying_crp on X)

flying_crp on X: with memory on, the digest in the agent's instructions
disagreed with the project's own rules, and things that belong in the
project were saved to memory instead, while the user keeps the
project's docs tidy themselves.

- The digest's header (internal/memory/digest.go) now puts the
  project's own instruction files (AGENTS.md and the like) and docs
  first: where a memory disagrees, the agent follows the files and
  says which memory is out of date. A project's rule or fact belongs in
  its files; memory keeps what holds for the user across projects.
- memory_save's description says the same, and a new save made in a
  project whose root holds AGENTS.md, CLAUDE.md, GEMINI.md,
  .github/copilot-instructions.md or .cursorrules ends with a note
  naming the files found: for a memory of the caller's project (any
  kind but profile and preference), to offer to write it there and
  forget the memory once it is; for a global rule or procedure, the
  same when it holds only in this project (projectFilesNote). The save
  itself is kept.
- Distillation's instructions leave a project's rules and conventions
  to its files, and drop what disagrees with them.
- The texts name neither magpie nor a vendor (checked in each test).
  The only filenames named are AGENTS.md "and the like" in the fixed
  text, and in the save note the files actually found on disk.
- docs/subsystems/memory.md says all three.

Tests, each red on the old code (the three source files put back to
origin/main by hand, tests kept), green with the change:
TestDigestDefersToTheProjectsFiles (internal/memory), TestWhatIsSent
(internal/memdistill), TestMemorySavePointsProjectRulesToItsFiles
(internal/gateway, -tags nogui).

Real agents, sandbox HOME and CLAUDE_CONFIG_DIR, model through the live
gateway as an endpoint only, nothing live written:
- Digest: a git project whose CLAUDE.md/AGENTS.md say "Python code here
  is indented with tabs", and a digest in the sandbox CLAUDE.md with a
  project memory "Indent Python code with 4 spaces". Asked to write
  add.py, with the old header Claude Code (haiku and sonnet) both used 4
  spaces, following memory; with the new header both used a tab and
  said the memory was out of date.
- Save: a sandbox `magpie serve` built from this tree on 127.0.0.1:3471,
  Claude Code (sonnet) with its memory server over --mcp-config, asked
  to "remember for this project: tests always run with pytest -x". The
  save came back with the note naming AGENTS.md, CLAUDE.md, and the agent
  offered to add the rule to them and then delete the memory.

Full suite (`go test -timeout 45m ./...`, mica):
- at a9696f14d: mica's disk filled during the run; reds in 17 packages
  were "no space left on device". Not counted.
- at 8647ac995 (origin/main + this): 101 ok, 3 red, each filed and not
  in code this change touches: internal/dirent watch tests (#7031),
  internal/gateway TestOpenCodeGoOwnFreeModelGetsNothingOfOpenCodes
  (#7117), internal/gui TestGatewayModeListsNoOwnSessions (#7064).
- at d67beb049 (this commit's tree, on origin/main 67405d560): 101 ok,
  the same 3 filed reds (#7031, #7117, #7064), nothing else.
GOOS=linux and GOOS=windows go vet of memory, memdistill and gateway:
ok. gofmt -l: clean. No GUI or i18n change, so no GUI suite run.

Not tried: Codex or other agents (Claude Code only); a memory server
reached from another computer (the note stats the project roots that
computer named, on this one: at worst an advisory note).
This commit is contained in:
yetone
2026-11-19 03:27:25 +08:00
parent 67405d5609
commit b332ef7efe
7 changed files with 168 additions and 6 deletions
+17 -2
View File
@@ -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`
+46 -2
View File
@@ -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) {
+65
View File
@@ -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)
}
}
+3 -1
View File
@@ -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"}]
+6
View File
@@ -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)
+1 -1
View File
@@ -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")
}
+30
View File
@@ -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)
}
}
}