Skip to content

Recall and learning in the coding agents' model endpoint - #22

Open
dcmcand wants to merge 12 commits into
mainfrom
feat/memory-mvp-2-proxy
Open

dcmcand wants to merge 12 commits into
mainfrom
feat/memory-mvp-2-proxy

Conversation

@dcmcand

@dcmcand dcmcand commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Slice 2: Recall and learning in the agent model proxy

Every coding-agent model call through the gateway now carries the person's memories, and what they type is learned in the background. A slow or down mem0 never breaks the agent or holds it past the recall limit. With memory off, the request to the provider and the stream back are byte for byte what they were.

Stacked on #20. Base this on feat/memory-mvp-1-core until #20 merges.

How it works (internal/ai/agentproxy):

  • Recall runs on every call except the agent's own housekeeping (pi 1.4.0's summarization calls, or user text over 8,000 runes). The query is the latest user message. Results come from a two-minute per-gateway cache, else a search bounded by memory.recallTimeout (2s). Up to five memories go into a note in the first message when it is a system message, or into a new system message at the front. The note goes at the front because some models (Qwen chat templates under vLLM, Anthropic, Bedrock) refuse a system message anywhere else.
  • Learning runs only on a turn the person typed (the last message is theirs), after the answer has streamed back, and only for a 2xx answer the agent received in full. "remember that ..." is stored word for word. Anything else goes to mem0 with the answer text and Tapas's extraction instructions from Memory core: remember, instructions, SSN check, retrying start check #20. At most four learn calls run at once, and further turns are skipped as busy.
  • Log lines: memory.recall_failed, memory.learn_panicked, memory.learned, memory.learn_failed, memory.learn_skipped (reason=busy|too_long) and memory.write_refused reason=ssn. They carry the user and counts, never the query, the typed text, the answer or memory text.

Contracts touched:

  • agentproxy.Proxy gains the optional Memory, Recall and RecallTimeout fields. Keyed literals are unaffected.
  • wiring.AgentModel takes the memory service, cache and recall timeout. Its only caller is servercmd/gateway.go.
  • The upstream chat completions body carries the note only when memory is on and something was recalled.
  • copyEvents also returns the error writing to the agent, so a disconnect is never learned.

Notes for review:

  • Learning runs in a goroutine on context.WithoutCancel. It is bounded by mem0's add client timeout (memory.addTimeout, 120s by default).
  • A panic inside the memory service during learning is recovered in the learn goroutine and logged as memory.learn_panicked (user and stack, never the panic value). The learn slot is still released.
  • The note's 2,500-character total cap is implemented but can't bind with five memories cut to 500 characters each.
  • apitest.Options.Memory sets memory on the fixture's agent model proxy, including one a test passes in.

Depends on: #20

Validation

Step Command Result
unit go test ./internal/ai/... ./internal/cli/... ./internal/gateway/... -race -count=1 ok
journeys go test ./internal/ai/agentproxy -run 'Remember|Recall|Learn|SSN|RecallFails|MemoryOff' -v every named test passes, including TestMemoryOffForwardsTheSameBytes, TestRecallFailsOpenWhenMemIsDownOrSlow, TestLearnRefusesSSNWithoutLoggingIt and TestLearnRunsAtMostFourAtOnce
full make test-local ok
full make test 154 packages ok. The same 4 local failures as #20, none in packages touched here: internal/files and internal/storage/hosthome fail on main too, and test/devenv and test/imagetag fail on my machine's commit signing and missing shasum.

…ed turns

With a Memory set, the coding agents' model endpoint now does two things
around each call.

Recall: the latest user message is the query. Results come from a
two-minute per-gateway cache or a search bounded by the recall timeout
(2s when unset). Up to five memories are added as a note to the first
message when it is a system message, or as a new system message at the
front. A failed or slow search is logged as memory.recall_failed
without the query, and the call goes on without a note.

Learning: after the answer has streamed to the agent, a turn the person
typed is learned in the background. "remember that ..." is stored
word for word with Remember. Anything else is sent to Add with the
answer text, up to 4,000 runes. At most four learn calls run at once,
and further turns are skipped as busy. Loop steps, failed answers,
agent disconnects, pi's summarization calls and pastes over 8,000
runes are never learned. Refusals, failures and successes are logged
by user and count only.

With Memory nil the upstream body and the stream are byte for byte as
before. copyEvents now also returns the error writing to the agent.
wiring.AgentModel takes the memory service, a recall cache and
memory.recallTimeout. The gateway builds the cache only when memory is
on and passes a nil interface when it is off, so a nil service never
looks like one. The cache stays in a variable for the memories API.

The apitest fixture gains Options.Memory. A gateway test checks that
alice's and bob's agent apps each recall with their own identity name
and get only their own note.
Learning runs in its own goroutine, outside the HTTP handler's recover,
so a panic in the memory service would have ended the gateway. The
goroutine now recovers it and logs memory.learn_panicked with the user
and the stack. It never logs the panic value, which may carry typed or
memory text. The learn slot is still released, so later turns keep
learning.
GET /api/memories lists what Tapas remembers about the signed-in
person, newest first. DELETE /api/memories/{id} removes one of theirs
and drops their recall cache entries, so a deleted memory is not
recalled again. Another person's id, or one that does not exist, is a
404.

Both routes refuse an app's or a job's own token. With memory off they
answer 404 "Memory is off on this platform.". When mem0 fails they
answer 502 "Memory could not be reached; try again later." and log
memory.list_failed or memory.delete_failed with the user.

ui/openapi.json and the generated UI client are regenerated.
Settings gains Memories, next to Secrets. It lists each memory with the
day it was saved and lets the person delete one after confirming. With
nothing saved it says so and hints at "remember that ...". With memory
off, or mem0 unreachable, it shows the server's message instead of a
list.
The admin memory page now describes what memory does: recall into the
admin's agent model calls, learning, "remember that ...", the SSN
refusal, the Memories page and API, memory.recallTimeout, every
memory.* log line, and the limits. It also fixes the start check
description, which now retries. The members' Ask AI page gains a
Memories section, and the Helm values example shows recallTimeout.
…orget recall results after a learn

A typed message over 8,000 characters was skipped from learning without a
log line; it now logs memory.learn_skipped reason=too_long, as the spec
says. pi's own summarization calls are still skipped silently.

After mem0 stores at least one memory, the person's cached recall results
are dropped, so asking the same thing again within two minutes recalls
what was just stored.
Memory off is an admin's choice, so the Memories page shows its banner in the info tone. Other errors stay red.
DELETE /api/memories/{id} now refuses every API token with 403, including
a coding agent's own token when its owner lets it act without asking, and
personal tokens. An agent can then never erase what is remembered about
its owner, even if a prompt talks it into trying. The route joins the
session-only routes in the token middleware, and the handler checks again.
Listing memories is unchanged.
Say that only an SSN written with dashes is refused, that deleting a
memory works only from the browser, that recall of a deleted memory can
last a couple of minutes, and that long typed messages log too_long.

@jbouder jbouder left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One change.

}
audit(person, model, in, outTok, result)
if ans != nil && resp.StatusCode/100 == 2 && werr == nil {
p.startLearning(r.Context(), person, text, ans.String())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A real agent disconnect still gets learned here, with a cut-off answer. The disconnect cancels r.Context(), the upstream read fails, and copyEvents returns a nil error (line 343 ignores sc.Err()), so werr stays nil. The brokenWriter test in learn_test.go:262 fails the write instead, so it doesn't cover this path. Returning sc.Err() from copyEvents and also requiring r.Context().Err() == nil before startLearning would close it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5882449, with both changes. The non-streamed path had the same hole: it ignored the io.ReadAll error, so a disconnect there learned the typed turn alone. It now carries the read error too.

I added five subtests to TestLearnSkipsFailedAnswers covering a cancelled context mid-stream, during a non-streamed answer, and at the end of a complete stream, plus an upstream connection drop in each path. I also checked that each part of the fix is needed: dropping sc.Err(), the read error, or the context check each makes its own test fail.

When an agent disconnected mid-answer, the cancelled request context
ended the upstream read, but copyEvents ignored sc.Err() and returned
nil, so the cut-off answer was learned. The non-streamed path ignored
the io.ReadAll error the same way, learning the typed turn alone.

copyEvents now returns the error that ended reading, the non-streamed
path carries its read error, and learning also requires the request
context to be live, which catches an agent that went away as the last
bytes of a complete answer were written.
@dcmcand
dcmcand changed the base branch from feat/memory-mvp-1-core to main December 1, 2026 17:21
@dcmcand
dcmcand requested a review from jbouder December 1, 2026 17:21
Memories: list and delete under Settings

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants