Storefront has been decoupled into micro-frontends with a dedicated commerce app and shared shell.

Read the architecture guide →

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.

November 5, 2026ProposedData

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

TermPlain-language meaningExampleHow it helps
Episodic memoryA 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 memoryA 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

  1. A customer states a book-related preference during a conversation.
  2. BookAgent answers normally; evaluating and saving new memory happens in the background so it does not delay the streamed response.
  3. Background processing may retain an eligible reading preference or a short interaction summary.
  4. In a later conversation, BookAgent receives relevant saved memory and uses it to tailor recommendations.
  5. 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

IncludedNot 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

  1. Verify the customer’s identity and retrieve a capped set of saved preferences and relevant, unexpired past episodes.
  2. Provide those results in BookAgent’s working context for this answer (omit the memory block entirely if nothing matches).
  3. Stream the answer using the current request, retrieved memory, and live Catalog facts.
  4. Submit the completed exchange to background processing without waiting for extraction to finish.
  5. 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

ChoiceReason
Separate episodes from preferencesA past event and a lasting preference have different meanings, update rules, and retention needs.
Similarity search for episodesFinds relevant past discussions without requiring the customer to repeat exact wording.
Structured storage for preferencesSupports predictable updates, inspection, conflict resolution, and deletion.
Application-controlled memory loadingThe system enforces retrieval limits consistently rather than relying on the model to request memory.
Background extractionSummarization and preference consolidation should not delay the customer’s streamed answer.
Explicit privacy processing in the workerResponse-path filtering alone must not be assumed to protect exchanges passed to background extraction.
Reuse existing infrastructureAvoids 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

AlternativeWhy it is not preferred in this proposal
Keep session-only memoryAvoids durable personal data, but does not solve cross-session continuity.
Vector store for both memory typesPossible, but structured preference updates and conflict handling are less straightforward.
Relational database with vector searchCould simplify storage, but introduces a second vector-search approach alongside BookWorm’s existing Qdrant pattern.
In-memory cache as primary storeDoes not follow durable persistence patterns; caching may be considered later as an optimization.
Durable folder for session filesDoes not by itself provide user-level search, ownership, retention, and deletion semantics.
Model-selected memory toolsMakes retrieval dependent on the model and changes the governed tool surface.
External managed memory serviceIntroduces another provider, operating cost, and data-residency review.

Open questions before acceptance

AreaDecision still required
Product and privacyIs memory opt-in, how is its use explained, and what customer-facing inspection, correction and deletion controls are required?
Memory policyWhich preference categories are allowed, what evidence is sufficient, and how are contradictions and stale preferences handled?
RetentionIs 90 days appropriate for episodes? What is the preference decay policy and deletion completion target?
PerformanceWhat are the retrieval latency budget, result and context-size caps, and timeout or store-outage behavior?
IdentityHow does verified end-user identity reach the provider for both AG-UI workflow handoffs and A2A callers?
FrameworkWhich lifecycle hooks and concurrency guarantees are available in the pinned Agent Framework version?
Background processingWhat queue capacity, overload policy, retry limits and loss-on-restart behavior are acceptable?
Consistency and deletionHow 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

AspectEpisodesPreferences
Proposed storeQdrant collection bookagent-episodes.PostgreSQL chat database, table user_preferences.
Saved informationUser 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.
RetrievalMandatory 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.
UpdatesAppend new episodes; remove expired or user-deleted entries.Insert or update preferences; repeated evidence can reinforce them and explicit corrections replace conflicting values.
RetentionProposed 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:

ComponentResponsibility
UserMemoryContextProviderResolve identity on every run, load bounded memory before the answer, and submit work after the run. Register through BookAgentRegistration.
IEpisodicMemoryStore and EpisodicMemoryEncapsulate user-filtered Qdrant search, writes, inspection, expiry and deletion.
IPreferenceStore, UserPreference and ChatDbContextEncapsulate user-owned preference queries, updates and deletion with EF Core migrations.
Background extraction serviceConsume an in-process Channel, call Presidio and the chat model, validate results and consolidate preferences.
AddUserMemory()Register stores, provider and worker.
User-memory endpointsLet 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 (1536 dimensions with cosine similarity); verify compatibility before creating the collection.
  • Agent & framework verification: Update book-agent.yaml to enforce trust rules without widening the agent’s tool permissions (note also FileMemoryProvider remains separate session-only work). Confirm AIContextProvider lifecycle hooks against the pinned Agent Framework version rather than treating this outline as an API contract.

Delivery sequence and acceptance verification

  1. Resolve product and technical open questions (identity, privacy, deletion, and failure behavior).
  2. Provision the Chat PostgreSQL database and Qdrant collection; implement stores, migrations, and lifecycle controls.
  3. Implement bounded retrieval and context injection, then background extraction and preference consolidation.
  4. Deliver authenticated inspection and deletion endpoints and customer-facing controls.
  5. Update agent guidance and verify acceptance scenarios before enabling durable memory.
ScenarioExpected result
Returning customerA relevant saved preference can influence a later session’s recommendation.
One-time or gift requestAn episode may describe the request, but it is not automatically saved as the customer’s lasting preference.
Different customers, including concurrent runsCustomer A cannot retrieve, change or delete customer B’s memory.
Missing or unverified identityNo personal memory is read or written.
No matching memoryNo memory block is injected and the agent makes no claim of recall.
Explicit correctionThe new statement takes precedence over a conflicting saved preference.
Private or sensitive contentProhibited content is rejected before persistence; identifying text is removed before model extraction.
Inspect and deleteThe customer can inspect both memory types and delete them without queued work restoring deleted data.
Expired episodeRetrieval excludes it, and cleanup removes it under the agreed retention policy.
Performance and failureRetrieval 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.