Skip to the page

Guides · Agents & copilots

Memory and context packs

Store bi-temporal facts, keep private per-caller scratchpad notes and assemble cited, token-budgeted context packs under your schema’s access rules.

What you’ll build#

You will wire a customer-support and account agent that remembers changing customer facts across two timelines, keeps private per-caller scratchpad notes for active tickets and assembles token-budgeted, citation-stamped prompts strictly under the signed-in user’s access policies.

Bi-temporal memory
Store facts that distinguish when something became true in the world from when your agent learned it, without overwriting history.
Working scratchpad
Keep short-lived, expiring per-caller notes for active tool runs without polluting long-lived account knowledge.
Live context packs
Fetch permitted rows, file passages, scratchpad notes and memory facts in one token-budgeted call with verifiable citations and an invalidation bookmark.

Your app or MCP client calls the model while Napalm owns isolation, historical accuracy, citations and per-root cleanup beneath every call.

Why bi-temporal memory matters#

Most agent memory setups dump summaries into a vector store or key-value table. When an account changes plans, the old summary either gets overwritten and lost forever or stays in the index beside the new summary so the model contradicts itself. Even worse, when a billing change takes effect retroactively, a single timestamp cannot tell what was true on a given date from what your agent knew when it sent an email.

Napalm solves this problem by storing every ext::napalm::MemoryFact on two clocks:

World validity time
validFrom through validTo records when a fact was actually true in the real world. An open-ended fact leaves validTo unset until superseded.
Commit time
committedAt and the transaction commit position (txLsn) record the exact moment your agent learned and stored the fact.

Worked scenario: Acme Corp’s billing plan#

Suppose Acme Corp upgrades its subscription on March 1, but your support agent does not hear about the upgrade until March 5. The agent records the Enterprise plan with validFrom: 2026-03-01 and Napalm stamps committedAt: 2026-03-05. Later, on April 1, Acme downgrades back to Pro. Instead of editing the old row in place or inserting a conflicting duplicate, the agent supersedes the Enterprise fact. In one atomic transaction, Napalm closes the Enterprise window at validTo: 2026-04-01 and opens the Pro fact starting at validFrom: 2026-04-01.

That two-clock model unlocks four guarantees that ordinary vector and key-value memory cannot provide:

CapabilityOrdinary vector or KV memoryNapalm bi-temporal memory
Retroactive truthOverwrites the old value or mixes both plans in top-k search results.Napalm bi-temporal memoryAnswers "What plan was Acme on March 15?" accurately with asOfValid, even though the upgrade was logged on March 5.
Audit and debuggingCannot reconstruct what the agent knew before a later update arrived.Napalm bi-temporal memoryAnswers "What did our agent believe on March 3 when it sent that email?" with asOfTx, proving the upgrade had not been logged yet.
Zero contradicting active factsStale and current summaries compete in retrieval until a manual cleanup script deletes old chunks.Napalm bi-temporal memoryAtomic supersession closes the old window when the replacement opens, and directed MemoryEdge links tie facts to real app records such as Account and Ticket.
Zero permission leaks and clean erasureSeparate memory stores duplicate tenant filters by hand and leave orphaned vectors behind after customer deletion.Napalm bi-temporal memoryEvery fact and scratchpad note inherits your schema’s compiled access rules and erases atomically when you erase its owning root.

Storing and superseding facts#

Each fact carries a kind (semantic for enduring truths, episodic for dated events or procedural for learned workflows), a subjectKey that groups statements about the same subject, an optional entityType and entityId linking the fact to a record in your schema, and a confidence score from 0 to 1.

Use client.memory.assertFact to record a new fact, client.memory.supersedeFact to replace an existing fact cleanly and client.memory.linkFacts to connect two facts with a directed ext::napalm::MemoryEdge. Superseding a fact closes its validity window and populates its typed superseded_by_fact link pointing straight to the replacement fact. When assertFact detects an overlapping fact on the same subjectKey, the response lists each conflict in contradictions so your agent can supersede the outdated record instead of leaving conflicting active facts.

agents/accountMemory.ts
// agents/accountMemory.tsimport { NapalmClient } from 'napalm-client' const client = new NapalmClient('https://s4p8m2k9vr.napalmcloud.com', {  token: process.env.SUPPORT_AGENT_TOKEN,}) // 1. On March 5, the agent learns Acme upgraded retroactively on March 1.const upgraded = await client.memory.assertFact({  kind: 'semantic',  entityType: 'default::Account',  entityId: acmeAccountId,  subjectKey: 'account:acme:plan',  content: 'Acme Corp is on the Enterprise billing plan ($2,400/month).',  confidence: 0.98,  validFrom: '2026-03-01T00:00:00Z',  tags: ['billing', 'plan'],}) // Record the support ticket event that triggered the later change.const ticketNote = await client.memory.assertFact({  kind: 'episodic',  entityType: 'default::Ticket',  entityId: downgradeTicketId,  subjectKey: 'ticket:4812:downgrade',  content: 'Acme finance requested a downgrade from Enterprise back to Pro effective April 1.',  confidence: 1,  validFrom: '2026-04-01T00:00:00Z',  tags: ['billing', 'ticket'],}) // 2. On April 1, supersede the Enterprise fact and open the Pro fact atomically.const downgraded = await client.memory.supersedeFact({  factId: upgraded.fact.id,  replacementContent: 'Acme Corp is on the Pro billing plan ($490/month).',  confidence: 1,  validFrom: '2026-04-01T00:00:00Z',  closeValidTo: '2026-04-01T00:00:00Z',  tags: ['billing', 'plan'],  reason: 'Downgrade requested in ticket #4812',}) // 3. Connect the new plan fact to the ticket fact with a directed temporal edge.await client.memory.linkFacts({  fromFactId: downgraded.replacementFact.id,  toFactId: ticketNote.fact.id,  relation: 'caused_by',  validFrom: '2026-04-01T00:00:00Z',})

External assistants connected over /mcp get the same operations through the built-in memory_assert, memory_query and memory_supersede tools. Read-only credentials see only read tools and cannot mutate stored memory.

MCP JSON-RPC calls
// tools/call memory_assert (March 5: record retroactive March 1 upgrade){  "jsonrpc": "2.0",  "id": 11,  "method": "tools/call",  "params": {    "name": "memory_assert",    "arguments": {      "kind": "semantic",      "entityType": "default::Account",      "entityId": "0195a7e2-3c10-7b9d-8a11-2c4e8f9b0101",      "subjectKey": "account:acme:plan",      "content": "Acme Corp is on the Enterprise billing plan ($2,400/month).",      "confidence": 0.98,      "validFrom": "2026-03-01T00:00:00Z",      "tags": ["billing", "plan"]    }  }} // tools/call memory_supersede (April 1: close Enterprise and open Pro atomically){  "jsonrpc": "2.0",  "id": 12,  "method": "tools/call",  "params": {    "name": "memory_supersede",    "arguments": {      "factId": "0195b8f0-91a2-74c3-9d02-7a1c5e3f9210",      "replacementContent": "Acme Corp is on the Pro billing plan ($490/month).",      "validFrom": "2026-04-01T00:00:00Z",      "closeValidTo": "2026-04-01T00:00:00Z",      "reason": "Downgrade requested in ticket #4812"    }  }}

Time-travel recall#

Query stored facts with client.memory.queryFacts (or MCP memory_query). You can filter by subjectKey, entityType, entityId, kind, tags or minConfidence, and combine lexical text matching with an optional queryEmbedding. Passing asOfValid and asOfTx lets you inspect either real-world history or the agent’s past knowledge state.

agents/timeTravel.ts
// Question A (world truth): "What plan was Acme actually on March 15?"const marchTruth = await client.memory.queryFacts({  subjectKey: 'account:acme:plan',  asOfValid: '2026-03-15T12:00:00Z',}) // Question B (agent belief): "What did our agent believe on March 3 when it sent that email?"const march3Belief = await client.memory.queryFacts({  subjectKey: 'account:acme:plan',  asOfValid: '2026-03-03T12:00:00Z',  asOfTx: '2026-03-03T12:00:00Z',}) // Question C (current truth): omit both clocks to query active facts right now.const currentPlan = await client.memory.queryFacts({  subjectKey: 'account:acme:plan',  tags: ['billing'],})
Returned facts
// marchTruth[0].fact -> matches the Enterprise fact (valid Mar 1 to Apr 1){  "subjectKey": "account:acme:plan",  "content": "Acme Corp is on the Enterprise billing plan ($2,400/month).",  "validFrom": "2026-03-01T00:00:00Z",  "validTo": "2026-04-01T00:00:00Z",  "committedAt": "2026-03-05T14:20:00Z"} // march3Belief -> [] (or Acme's prior Starter fact) because the Enterprise upgrade// was not committed until March 5, explaining why the March 3 email cited the old plan. // currentPlan[0].fact -> matches only the open Pro fact (validFrom Apr 1, no validTo){  "subjectKey": "account:acme:plan",  "content": "Acme Corp is on the Pro billing plan ($490/month).",  "validFrom": "2026-04-01T00:00:00Z",  "committedAt": "2026-04-01T09:05:00Z"}

Direct EdgeQL time-travel#

You can also run bi-temporal time-travel directly inside ordinary EdgeQL or deployed queries using ext::napalm::memory_as_of(...). Every returned fact obeys your compiled access policies and exposes the typed superseded_by_fact link so queries can follow replacement chains without manual string joins:

dbschema/queries/memoryAsOf.edgeql
# Query bi-temporal memory directly in ordinary EdgeQL or a deployed query# and follow the typed superseded_by_fact link to inspect replacements.select ext::napalm::memory_as_of(<datetime>'2026-03-15T00:00:00Z') {  subject_key,  content,  superseded_by_fact: { fact_id },};

Per-caller working scratchpad#

Not every observation belongs in long-lived bi-temporal memory. While an agent works through a multi-step ticket, it often needs a private notepad for partial invoice calculations, intermediate tool results or a checklist that should vanish once the task finishes. Putting ephemeral drafts into MemoryFact clutters long-term account history.

NeedScratchpad (client.scratchpad)Bi-temporal memory (client.memory)
LifetimeShort-lived working state with optional ttlSeconds expiry (60 seconds to 365 days) and manual forget().Bi-temporal memory (client.memory)Long-lived auditable history preserved across atomic supersessions.
UpdatesUpserts in place by (namespace, key) for fast working-note edits.Bi-temporal memory (client.memory)Immutable facts closed via supersedeFact() so old beliefs remain queryable.
IsolationPrivate to the authenticated caller and root (ext::napalm::AgentNote).Bi-temporal memory (client.memory)Scoped to the caller and owning root (ext::napalm::MemoryFact) with optional entity links.
MCP toolsremember, recall, forget.Bi-temporal memory (client.memory)memory_assert, memory_query, memory_supersede.
agents/scratchpad.ts
// Store a short-lived working note scoped to this caller and ticket.await client.scratchpad.remember({  namespace: 'ticket-4812',  key: 'refund-check',  body: 'Checked Stripe invoice inv_981. Prorated Enterprise credit is $620. Waiting on finance sign-off.',  tags: ['billing', 'in-progress'],  ttlSeconds: 86_400, // expires automatically after 24 hours  targetType: 'default::Ticket',  targetId: downgradeTicketId,}) // Recall relevant non-expired notes later in the same session or a resumed turn.const notes = await client.scratchpad.recall({  query: 'prorated credit amount',  namespace: 'ticket-4812',  limit: 5,}) // Clear working notes once the ticket closes.await client.scratchpad.forget({  namespace: 'ticket-4812',  allInNamespace: true,})

Policy-compiled live context packs#

Building a grounded agent prompt usually requires stitching together four separate pieces of infrastructure: a vector database for file chunks, an application database for structured rows, a memory store for agent notes, and custom middleware to re-check permissions, count tokens and invalidate stale prompts. One missed permission filter in that glue code leaks another tenant’s records straight into the model prompt.

POST /context, client.context.getContext and the MCP get_context tool replace that custom retrieval stack with one database-native call. Napalm gathers matching records across four sources in a single policy-checked pass:

Four unified sources
Combines permitted database rows (row), indexed document passages (file_passage), caller scratchpad notes (scratchpad_note) and bi-temporal facts (memory_fact).
Compiled access rules
Every candidate runs under the authenticated caller’s schema policies before ranking, so restricted rows never enter the candidate set or token budget.
Token budget and citations
Packs the highest-scoring items inside maxTokens and stamps every item with a verifiable citation handle ([c1], [c2], …) carrying (objectType, objectId, field, lsn).
Live invalidation bookmark
Returns an invalidationBookmark plus citedTypes and citedObjectIds so long-lived chat sessions detect immediately when any cited record or access rule changes.
agents/contextPack.ts
// Assemble one policy-filtered, token-budgeted prompt pack across all four sources.const pack = await client.context.getContext({  query: 'Acme billing plan history and open downgrade ticket',  maxTokens: 2048,  maxItems: 12,  includeSources: ['row', 'file_passage', 'scratchpad_note', 'memory_fact'],  asOfValidTime: '2026-04-02T10:00:00Z',  minScore: 0.25,}) // Feed cited snippets directly into your model prompt.const promptContext = pack.items  .map((item) => `[${item.citationId}] (${item.sourceKind}) ${item.text}`)  .join('\n\n') // Every citation carries the exact record, field and commit position (lsn).for (const cite of pack.citations) {  console.log(cite.citationId, cite.objectType, cite.objectId, cite.field, cite.lsn)} // Keep invalidationBookmark so an open session knows when any cited row or policy changes.console.log({  tokensUsed: pack.totalTokens,  truncated: pack.truncated,  bookmark: pack.invalidationBookmark,  citedIds: pack.citedObjectIds,})

Check memory isolation and citations#

Before enabling a support or account agent in production, verify caller reach, citation provenance and root cleanup against a branch:

Terminal
# 1. Verify which rows the signed-in user or agent credential can reach.napalm people reach support alice@acme.example.com # 2. Trace why a specific account row is allowed or hidden for that caller.napalm explain-access support Account 0195a7e2-3c10-7b9d-8a11-2c4e8f9b0101 --as alice@acme.example.com # 3. Preview per-root erasure to confirm memory facts and scratchpad notes erase with the root.napalm placement erase-root support 0195a7e2-3c10-7b9d-8a11-2c4e8f9b0101 --plan
Read-only callers
Connect with a --read-only key and confirm recall, memory_query and get_context succeed while remember, memory_assert and memory_supersede are withheld.
Citation verification
Confirm every objectId in pack.citations belongs to a record the signed-in caller can reach according to napalm explain-access.
Per-root erasure
Run napalm placement erase-root --plan on a test tenant root and confirm the erasure plan covers both application rows and the root’s bound memory facts and scratchpad notes.

Next steps#

Durable loops and swarms
Pause multi-turn agent loops at zero idle compute and coordinate specialist swarms on one database record.
MCP memory and context tools
Reference table for every built-in MCP memory, scratchpad and context tool.
Watching and stopping an agent
Inspect replayable traces, count credential reach, revoke access and undo a caller’s writes.