ADR-006: Add user-scoped episodic and semantic memory to BookAgent
Proposes private, cross-session memory so BookAgent can use past book discussions and stated reading preferences, while giving users control over stored information.
1. Context & Problem
Business problem
BookAgent helps customers find books and receive personalized recommendations. Today, a returning customer cannot rely on the agent remembering reading preferences from an earlier session. Customers have to repeat the same preferences, and recommendations lack continuity across visits.
We want BookAgent to use relevant book information that a customer previously shared, without building an unrestricted personal profile or retaining full chat transcripts.
Two different kinds of memory
| Term | Plain-language meaning | Example | How it helps |
|---|---|---|---|
| Episodic memory | A short account of a particular past interaction. | “The customer asked for a short mystery novel for a weekend trip.” | Recalls a relevant past discussion when a similar request arises. |
| Semantic memory | A reading preference explicitly stated by the customer, retained beyond one interaction. | “I prefer English-language mysteries and avoid horror.” | Guides future recommendations without asking the same preference questions again. |
A one-time request is not automatically a lasting preference. Asking for a gift for someone else must not become a preference attributed to the customer.
Relationship to existing behavior
Existing session memory supports work within a single active conversation only; it is not a durable, user-scoped memory service. Chat workflow session state remains transient under ADR-004: Keep Chat workflow sessions in memoryDecision Recordv1.0.0ADR-004: Keep Chat workflow sessions in memoryThe Chat workflow uses an in-memory session store and does not treat conversation history as durable business data.Ownerai-capabilities-teamOpen docs.
2. Business Value
- Better returning-customer experience: Customers repeat fewer reading preferences across sessions and receive more relevant recommendations.
- Continuity with customer control: Recommendations reflect earlier discussions while honoring explicit corrections and giving customers inspection and deletion rights.
- Privacy-by-design boundaries: Separates fleeting one-off gift requests from lasting preferences, excludes sensitive personal topics, and strips identifying text before saving.
- Operational efficiency: Reuses BookWorm’s existing database, vector search, and privacy-filtering patterns rather than introducing an external managed memory vendor.
3. How It Works
BookAgent is backed by two private, user-scoped memory stores—one for past interaction summaries (episodes) matched by meaning, and one for structured reading preferences that can be inspected, corrected, and deleted. The application automatically loads relevant memory before BookAgent answers rather than letting the AI model decide when to request memory.
Expected customer experience
- A customer states a book-related preference during a conversation.
- BookAgent answers normally; evaluating and saving new memory happens in the background so it does not delay the streamed response.
- Background processing may retain an eligible reading preference or a short interaction summary.
- In a later conversation, BookAgent receives relevant saved memory and uses it to tailor recommendations.
- The customer can inspect and delete stored memory at any time. Explicit corrections take precedence over older preferences.
New memory is not guaranteed to be available immediately after an answer because extraction runs asynchronously in the background. The agent must never claim something was saved unless persistence has been confirmed.
Scope and boundaries
| Included | Not included |
|---|---|
| Private memory tied to a verified customer identity. | Shared memory across customers or an inferred identity from message text. |
| Short book-related interaction summaries and explicitly stated reading preferences. | Full transcript storage or inferred personal characteristics. |
| Reading, updating and deleting memory owned by Chat. | Changes to Catalog books, Reviews feedback, Baskets or Orders. |
| Use of retrieved memory by BookAgent. | Giving every agent access to the customer’s memory. |
| Retention and deletion controls for both stores. | Treating session files as the durable customer profile. |
Catalog remains the source of truth for book facts. A remembered conversation is never evidence that a book’s price, availability, or rating is still current.
Privacy, identity, and trust rules
- Verified identity required: Resolve the authenticated customer on every invocation. Never reuse one user’s identity across requests or accept a user identifier written in chat text as authorization. Without a verified identity, do not read or write personal memory.
- Strict user isolation: Apply the same user boundary across retrieval, background writes, inspection, and deletion.
- De-identification and sensitive-topic exclusion: Remove identifying personal text before running extraction or storing summaries, keeping only the user identifier needed to enforce ownership. Exclude sensitive topics—including health, religion, and political views—from both episodes and preferences, as anonymization alone does not make such content safe to retain.
- Evidence-grounded retention: Save only eligible information directly grounded in customer statements, not model guesses, and validate extraction results before persisting.
- Safe grounding in responses: Treat retrieved memory strictly as reference data, not instructions that override agent policies. Only refer to a past interaction when supporting memory was actually retrieved; if none was retrieved, do not pretend to remember.
- Complete deletion: Inspection and deletion must cover both stores, and pending background work must not silently recreate information a customer has already deleted.
Runtime flow
- Verify the customer’s identity and retrieve a capped set of saved preferences and relevant, unexpired past episodes.
- Provide those results in BookAgent’s working context for this answer (omit the memory block entirely if nothing matches).
- Stream the answer using the current request, retrieved memory, and live Catalog facts.
- Submit the completed exchange to background processing without waiting for extraction to finish.
- Anonymize the exchange, extract candidate memories, reject prohibited or unsupported content, and write eligible results to the appropriate store.
Loading graph...
Latency note: Only memory extraction runs outside the response path. Pre-answer retrieval still adds time, so a retrieval latency budget, timeout behavior, and measurable release target must be agreed before acceptance.
4. Trade-offs & Lessons Learned
Design rationale
| Choice | Reason |
|---|---|
| Separate episodes from preferences | A past event and a lasting preference have different meanings, update rules, and retention needs. |
| Similarity search for episodes | Finds relevant past discussions without requiring the customer to repeat exact wording. |
| Structured storage for preferences | Supports predictable updates, inspection, conflict resolution, and deletion. |
| Application-controlled memory loading | The system enforces retrieval limits consistently rather than relying on the model to request memory. |
| Background extraction | Summarization and preference consolidation should not delay the customer’s streamed answer. |
| Explicit privacy processing in the worker | Response-path filtering alone must not be assumed to protect exchanges passed to background extraction. |
| Reuse existing infrastructure | Avoids introducing another database or external managed memory provider solely for this feature. |
Costs, risks, and operational considerations
- Dual-store operational duties: Chat gains database schema lifecycle, vector collection operations, and cross-store deletion responsibilities without an atomic cross-store transaction—requiring explicit consistency rules for concurrent conversations and partial writes.
- Model cost and background reliability: Extraction and embeddings add model usage and background workload. Because the proposed in-process queue is non-durable, pending extraction can be lost on service restart; acceptable loss, overload handling, and retries must be agreed.
- Extraction accuracy: Model-generated memories can be inaccurate; validation, customer inspectability, and correction controls are essential, and confidence scores alone do not eliminate this risk.
- User-linked data & latency: Even with identifying text stripped, stored summaries remain user-linked data. Retrieval adds latency and consumes prompt context space, requiring strict caps on both result counts and text length.
Alternatives considered
| Alternative | Why it is not preferred in this proposal |
|---|---|
| Keep session-only memory | Avoids durable personal data, but does not solve cross-session continuity. |
| Vector store for both memory types | Possible, but structured preference updates and conflict handling are less straightforward. |
| Relational database with vector search | Could simplify storage, but introduces a second vector-search approach alongside BookWorm’s existing Qdrant pattern. |
| In-memory cache as primary store | Does not follow durable persistence patterns; caching may be considered later as an optimization. |
| Durable folder for session files | Does not by itself provide user-level search, ownership, retention, and deletion semantics. |
| Model-selected memory tools | Makes retrieval dependent on the model and changes the governed tool surface. |
| External managed memory service | Introduces another provider, operating cost, and data-residency review. |
Open questions before acceptance
| Area | Decision still required |
|---|---|
| Product and privacy | Is memory opt-in, how is its use explained, and what customer-facing inspection, correction and deletion controls are required? |
| Memory policy | Which preference categories are allowed, what evidence is sufficient, and how are contradictions and stale preferences handled? |
| Retention | Is 90 days appropriate for episodes? What is the preference decay policy and deletion completion target? |
| Performance | What are the retrieval latency budget, result and context-size caps, and timeout or store-outage behavior? |
| Identity | How does verified end-user identity reach the provider for both AG-UI workflow handoffs and A2A callers? |
| Framework | Which lifecycle hooks and concurrency guarantees are available in the pinned Agent Framework version? |
| Background processing | What queue capacity, overload policy, retry limits and loss-on-restart behavior are acceptable? |
| Consistency and deletion | How are duplicate work, concurrent corrections, partial writes and deletion racing with extraction handled? |
5. Technical Reference
Status note: The implementation details below are design candidates from code review; framework hooks, identity propagation, and configuration must be verified against the pinned codebase before delivery.
System topology
Loading graph...
Storage and lifecycle specifications
| Aspect | Episodes | Preferences |
|---|---|---|
| Proposed store | Qdrant collection bookagent-episodes. | PostgreSQL chat database, table user_preferences. |
| Saved information | User id, summary, referenced book ids, creation and expiry times, and a vector representation for similarity search. | User id, preference kind and value, confidence, evidence count and last-seen time. |
| Retrieval | Mandatory user filter, relevance and recency ranking, proposed limit of 3-5 episodes. | User-filtered list ranked by confidence and recency, with a fixed result cap. |
| Updates | Append new episodes; remove expired or user-deleted entries. | Insert or update preferences; repeated evidence can reinforce them and explicit corrections replace conflicting values. |
| Retention | Proposed 90 days, configurable and subject to approval. | Until user deletion or an agreed decay policy removes stale preferences. |
- Confidence is a processing signal, not proof that a preference is correct; decay reduces older information weight over time (the decay rules are not yet defined).
- An expiry timestamp alone does not delete a record; implementation must exclude expired episodes from retrieval and provide a cleanup mechanism for physical deletion.
Developer implementation outline
Proposed code belongs in Chat/Memory/, following existing BookWorm patterns:
| Component | Responsibility |
|---|---|
UserMemoryContextProvider | Resolve identity on every run, load bounded memory before the answer, and submit work after the run. Register through BookAgentRegistration. |
IEpisodicMemoryStore and EpisodicMemory | Encapsulate user-filtered Qdrant search, writes, inspection, expiry and deletion. |
IPreferenceStore, UserPreference and ChatDbContext | Encapsulate user-owned preference queries, updates and deletion with EF Core migrations. |
| Background extraction service | Consume an in-process Channel, call Presidio and the chat model, validate results and consolidate preferences. |
AddUserMemory() | Register stores, provider and worker. |
| User-memory endpoints | Let an authenticated customer inspect and delete their own saved memory. |
- Infrastructure & embeddings: Wire the Chat PostgreSQL database and Qdrant collection in the service host configuration. The proposed episode embedding uses the existing Cohere Embed v4 pattern (
1536dimensions with cosine similarity); verify compatibility before creating the collection. - Agent & framework verification: Update
book-agent.yamlto enforce trust rules without widening the agent’s tool permissions (note alsoFileMemoryProviderremains separate session-only work). ConfirmAIContextProviderlifecycle hooks against the pinned Agent Framework version rather than treating this outline as an API contract.
Delivery sequence and acceptance verification
- Resolve product and technical open questions (identity, privacy, deletion, and failure behavior).
- Provision the Chat PostgreSQL database and Qdrant collection; implement stores, migrations, and lifecycle controls.
- Implement bounded retrieval and context injection, then background extraction and preference consolidation.
- Deliver authenticated inspection and deletion endpoints and customer-facing controls.
- Update agent guidance and verify acceptance scenarios before enabling durable memory.
| Scenario | Expected result |
|---|---|
| Returning customer | A relevant saved preference can influence a later session’s recommendation. |
| One-time or gift request | An episode may describe the request, but it is not automatically saved as the customer’s lasting preference. |
| Different customers, including concurrent runs | Customer A cannot retrieve, change or delete customer B’s memory. |
| Missing or unverified identity | No personal memory is read or written. |
| No matching memory | No memory block is injected and the agent makes no claim of recall. |
| Explicit correction | The new statement takes precedence over a conflicting saved preference. |
| Private or sensitive content | Prohibited content is rejected before persistence; identifying text is removed before model extraction. |
| Inspect and delete | The customer can inspect both memory types and delete them without queued work restoring deleted data. |
| Expired episode | Retrieval excludes it, and cleanup removes it under the agreed retention policy. |
| Performance and failure | Retrieval meets the agreed latency budget; extraction does not delay streaming; failures and dropped work are observable. |
- Testing guidance: Use deterministic embedding fakes for retrieval tests and PostgreSQL/Qdrant integration tests for isolation and deletion, covering concurrent runs, partial failures, and pending-work deletion races.