Arc Labs
BrainDocsPricing
GitHubSign inGet Started
EngineeringOperations

Tracing a Memory Back to Its Source

Arc Labs Engineering·May 7, 2026·16 min read
TL;DR

There is no Provenance struct and no trace ids. `memoryInspect` returns the write-time artifact (vector, keyword fields, HyPE questions, the extractor's derived graph, and the WAL `lsn`); the statement carries `extractorId`, `extractedAtUnixNanos` and `schemaVersion`, and `statementHistory` carries the supersession chain. The batch identity is the SESSION — client-chosen, and `deleteSession` is the one-call rollback — so choose it before the write, not after.

Memory systems fail in a particular way that's different from most software bugs: the wrong information gets stored correctly. The pipeline didn't crash. The extraction ran successfully. The LLM returned a well-formed response. But somewhere in the interpretation of a conversation, a fact got slightly wrong, an entity got misidentified, or a preference got inverted. The stored memory looks legitimate — it has high confidence, proper type, correct scope — and it will surface in retrieval for as long as it exists.

The standard debugging toolkit doesn't help much here. Stack traces, error logs, exception handlers — none of these fire when a memory is wrong but valid. What you need is the ability to trace the memory back to the conversation that created it, understand what the extractor saw and concluded, and either correct the memory or discard it.

That's what provenance is for. Every memory in Brain carries a Provenance struct as a first-class field. Not in the logs, not in a separate audit table that gets pruned — embedded directly in the memory itself, persistent as long as the memory persists.

What provenance actually is

There is no Provenance struct, no source_turn_ids, no extracted_by and no extraction_trace_id. Brain does not issue trace ids, and nothing links a memory to a pipeline execution. What it keeps instead is in two places, and the split is the thing to understand.

On the memory: the write-time artifact. memoryInspect returns what the write path produced for that text — not a log of what it did, but the material it derived:

const { memoryId, text, artifact, edges } = await brain.memoryInspect(id);

// artifact.record       — the stored record: kind, salience, createdAtUnixNanos,
//                         occurredAtUnixNanos, vectorDim, textLen, and `lsn`,
//                         the WAL log sequence number that fixes write order
// artifact.vector       — the embedding the semantic lane searches
// artifact.keywordFields — what the lexical lane indexed, per field
// artifact.hypeQuestions — the hypothetical questions generated for this memory
// artifact.graph        — the extractor's write-time knowledge graph:
//                         nodes {id, name, kind, typeQname} and
//                         edges {source, target, predicate, kind, confidence}
// edges                 — memory↔memory edges, both directions, from `link`

artifact.graph is the closest thing to "what the extractor concluded", and it is distinct from edges: the graph is what extraction derived at write time and never contains an edge you asserted through link.

On the statement: who derived the claim, and when. The typed graph carries the provenance fields the memory does not:

FieldAnswers
extractorIdWhich extractor produced it — 0 means written directly
extractedAtUnixNanosWhen it was produced, as distinct from when the content happened
eventAtUnixNanosWhen the thing it describes was true
schemaVersionWhich schema version the predicate was written against
version, supersedes, supersededByPosition in the revision chain
chainRootThe claim's stable identity across every revision
tombstoned, tombstonedAtUnixNanos, tombstoneReasonWhether, when and why it was retired

And createStatement takes evidence: string[] — the memory ids a claim rests on. That is the link from claim to source, and it is the one you control: nothing populates it for you on a direct write.

The session is the thread that connects them

The useful property the original of this page attributed to a trace id is real — it is just keyed on the session, which is a first-class dimension rather than an opaque id.

A session id is client-chosen, so your own conversation id can be the session id with no mapping table:

await brain.createSession({ sessionId: conversationId, title: "Support #4812" });

await brain.encode({ text: turn, session: conversationId });

That makes the session the batch identity for everything downstream:

// Read scoped to one conversation.
const answer = await brain.recall(
  new RecallBuilder(cue).sessions([conversationId]).build(),
);

// A structured query, same dimension.
await brain.queryTrace({ text: cue, sessions: [conversationId] });

// What a session holds.
const { sessions } = await brain.listSessions();
// each: { sessionId, createdAtUnixNanos, lastActiveUnixNanos, title, memoryCount }

There is no batch id below that. One encode writes one memory — there is no remember({ turns }) producing N memories that share an identity — so if you need a run to be revocable as a unit, give it its own session. That is the decision to make before the write, not after.

Debugging: "This memory is wrong"

A user reports the agent said "your manager at Arrive is Sarah" when the answer is Priya. Start at the memory:

const { text, artifact, edges } = await brain.memoryInspect("mem_8B3C");

console.log(text);
// "Georgian's manager at Arrive is Sarah"

// Which session it came from is NOT on the memory — ask the session dimension
// instead by recalling within each candidate session, or keep your own
// memoryId -> conversation mapping at write time. Brain stores the text you
// sent, not the turns it came from; those live in your system.

console.log(artifact.record?.lsn);        // write order, for "what landed when"
console.log(artifact.graph?.edges);       // what the extractor concluded
// [{ source: "georgian", target: "sarah", predicate: "manages",
//    kind: "relation", confidence: 0.82 }]

artifact.graph is where a misreading shows up: the extractor's own nodes and edges, with the confidence it assigned. If the predicate direction is inverted or the object resolved to the wrong entity, it is visible here before you look at anything else.

Then follow the claim, not the memory. The statement is what retrieval answers from, and it is the thing with a history:

const { statements } = await brain.listStatements({
  subject: georgianEntityId,
  predicate: "manages",
  onlyCurrent: false,          // include superseded revisions
  includeTombstoned: true,
  limit: 100,
});

for (const st of statements) {
  console.log(st.version, st.object, st.confidence, st.extractorId, st.schemaVersion);
}

extractorId tells you whether a human or an extractor asserted it, and schemaVersion tells you which schema's meaning of manages was in force. Neither is recoverable from the memory alone.

Correcting it is a supersede, not an edit — the wrong claim stays readable as a prior revision:

await brain.supersedeStatement(wrongStatementId, {
  kind: "fact",
  subject: georgianEntityId,
  predicate: "manages",
  object: { entity: priyaEntityId },
  confidence: 1.0,
  evidence: [correctingMemoryId],   // cite the memory that establishes it
});

Debugging: "This whole batch came out wrong"

You changed your extraction prompt last Tuesday and processed 400 conversations before noticing the new prompt was extracting preferences as facts, losing the versioning semantics. You need to roll back that period.

There is no trace to roll back. No listTraces, no forgetByTrace, no restoreByTrace. What there is, and it does the job, is the session:

// The sessions in the space, with when each was last active.
const { sessions } = await brain.listSessions();

const affected = sessions.filter(
  (sn) =>
    sn.lastActiveUnixNanos >= deployedBadPromptUnixNanos &&
    sn.lastActiveUnixNanos <= revertedUnixNanos,
);

// Soft by default. `hard: true` is the irreversible form and has to be
// asked for by name — a deliberate asymmetry, because a rollback is more
// often too wide than too narrow.
for (const sn of affected) {
  const res = await brain.deleteSession(sn.sessionId);
  console.log(`session ${sn.sessionId}: forgot ${res.memoriesForgotten}`);
  // res.existed tells "did something" from "already gone" — the op is
  // idempotent, so a resumed run is safe.
}

This is why the session decision belongs before the write: a run that gets its own session is revocable in one call per session, and a run that shares a session with ordinary traffic is not separable afterwards at all. If the bad batch was interleaved into live conversations, you are down to per-memory forget({ memoryId }) over a time window from memoryList({ dir: "desc" }), selected by your own records of what you wrote.

Soft delete is not an undo. It keeps the rows and stops reads returning them, which is the right default — but there is no restore verb. No restoreByTrace, no clearing a deleted_at. Putting a claim back means asserting it again. So the recovery path soft delete buys you is "the data has not been destroyed and an operator can go get it", not "one call reverses this."

There is no audit log

There is no audit API. No auditLog verb, nothing to query operation history with, and no actor or reason on forget, deleteSession or any tombstone — deleteSession takes a session id and an optional hard, and nothing else. Recording who ran a rollback, when, and why is your application's job, in your own logs.

One exception, and it is narrow: mergeEntities takes a reason and returns an auditId plus a gracePeriodSeconds within which unmergeEntity can reverse it. So a merge is recorded internally — which is why that call is single-shot and must not be retried — but no verb reads those records back.

What Brain does keep is the revision history of surviving claims: statementHistory(statementId) returns the supersession chain with version, supersedes, supersededBy, extractorId, extractedAtUnixNanos, tombstonedAtUnixNanos and tombstoneReason per revision. That is provenance for what is still there, not a ledger of what was done to it.

Debugging: "Why didn't this memory surface?"

The hardest class of retrieval bug: a memory you know exists did not appear for a query that should have matched it.

There is no debugRetrieval, and nothing takes an expected_memory_id. Ask the recall for its trace and look for the id yourself:

const answer = await brain.recall({
  query: "what does my manager prefer for code reviews?",
  maxResults: 5,
  includeTrace: true,
});

// A JSON STRING — its ids are 128-bit integers a JSON number would round.
const trace = parseWithBigInts(answer.trace!);

The trace carries every candidate each lane considered, plus the fusion, the filter chain and the rerank pass. That is enough to place the memory in one of three states, which is what the invented debug call was really for:

  • In a lane's candidates and in answer.memories — it surfaced; the problem is ranking, not retrieval.
  • In a lane's candidates but not in the answer — the filter chain or the relevance band dropped it.
  • In no lane's candidates — nothing retrieved it.

For the third case, go to the memory and compare what the lanes index against what you asked:

const { artifact } = await brain.memoryInspect("mem_7A2B");
artifact.keywordFields;   // what the lexical lane has, per field
artifact.hypeQuestions;   // the phrasings the semantic lane was given

A vocabulary gap shows up immediately here: if the memory says "prefers inline comments" and the query asks about "code review style", neither the keyword fields nor the generated questions contain the query's words, and no threshold change fixes that. Richer text at write time does.

Note what is not adjustable from the client: the relevance band, the fusion k and the lane thresholds are server-side policy, not request parameters. RecallInput is { query, maxResults, subject, scope, includeTrace } — there is no top_k cutoff to raise and no min_similarity to lower per call. Widen the read with maxResults, or widen it across spaces with scope: "namespace"; otherwise the fix is the memory's text or the engine's configuration, not the call.

The revision chain, in place of an audit ledger

There is no audit ledger. No auditLog verb, no audit_id, no actor, no event_type, no before/after snapshots, and no retention policy to tune — because none of it is written. A rollback leaves no record in Brain that it happened.

What exists is narrower and, for the question "why does this claim say what it says", more useful: the supersession chain on a statement.

const history = await brain.statementHistory(statementId, {
  includeTombstoned: true,
  limit: 100,
});

console.log(history.totalVersions);  // how many revisions the claim has had
console.log(history.chainRoot);      // its stable identity across all of them

for (const rev of history.items) {
  console.log({
    version: rev.version,                   // 1-based position in the chain
    object: rev.object,                     // what it asserted
    confidence: rev.confidence,
    supersedes: rev.supersedes,             // the revision it replaced
    supersededBy: rev.supersededBy,         // absent while current
    extractorId: rev.extractorId,           // 0 = written directly
    extractedAt: rev.extractedAtUnixNanos,  // when it was derived
    schemaVersion: rev.schemaVersion,       // whose meaning of the predicate
    tombstonedAt: rev.tombstonedAtUnixNanos,
    tombstoneReason: rev.tombstoneReason,
  });
}

Three things to know about reading it. statementId changes on every supersede, so chainRoot is the key to group revisions by and the id to store anywhere durable. A plain statement read follows supersession by default, so asking for an old id hands you the current head unless you say otherwise. And this is per-statement — there is no chain for a memory, because a memory's text is immutable once written and has no revisions to have.

The honest summary: Brain records what a claim has been, not what was done to the store. If you need the second — who ran a rollback, under which credential, with what reason — write it in your own logs at the moment you call, because nothing recovers it afterwards.

What the system guarantees, and what it does not

The two invariants this section used to claim — that every memory carries at least one source turn id, and that a memory's scope must match its source turns' — rest on fields that do not exist. There are no source turn ids, so neither can be enforced and neither is.

What is actually guaranteed:

Durability before acknowledgement. Nothing returns success until its WAL record is fsynced, and artifact.record.lsn is the log sequence number that fixes the write's position in that log. "Did this land, and in what order" is answerable; "which turn produced it" is not.

Space isolation. A credential is scoped to a space, and a caller cannot address another one — there is no scope parameter to get wrong. Cross-space reads happen only through scope: "namespace" on a recall, deliberately. whoami() returns the { namespace, spaceId, permissions } a credential actually has, which is how you check what a key can see rather than assuming.

Claims keep their history. A supersede builds a chain rather than overwriting, and a tombstone keeps the row. So the past of a claim survives even when its current value changes.

What is not guaranteed, and worth designing around: that a memory can be traced to the conversation turn behind it. Brain stores the text you sent. If the link back matters, you make it — by giving the run its own session, by putting the citation in the memory text, or by populating evidence on the statements you assert.

Practical discipline

Four habits follow from the real surface, and the first one is the only decision that cannot be made after the fact:

  1. Choose the session before the write. It is the only batch identity, it is client-chosen so your conversation id can be it directly, and deleteSession is the only one-call rollback. A run that shares a session with live traffic cannot be separated later.
  2. Populate evidence on statements you assert directly. Nothing fills it in for you on a direct write, and it is the only link from a claim to the memories it rests on.
  3. Put the citation in the text. The lexical lane indexes it, so a source in the text is both provenance and a retrieval key. A source kept only in your own database is neither.
  4. Log your own mutations. Brain records no actor and no reason for a forget, a tombstone or a session delete. If you will need to explain a rollback later, write that down when you run it.

For day-to-day operations the metrics are the right tool — particularly brain_extractor_schema_filtered_total and brain_extractor_resolver_outcome_total, which move when extraction and your schema drift apart or entity resolution turns ambiguous. For targeted investigation, memoryInspect, statementHistory and a recall with includeTrace are the three calls that answer most questions.

Reading the recall trace in depth

The trace is a JSON string, so the field names below are what you find after parsing it rather than a typed response — and the interpretation is the part worth having, because the numbers mean the same thing regardless of where you read them.

Which lanes found it. Brain fans out across semantic (dense vector), lexical (BM25 over tantivy), entity-graph, temporal and type lanes in parallel, and the trace lists every candidate each one considered. A memory absent from the lexical lane's candidates when its key terms are in the text usually means those terms are not discriminative in this space — a term appearing in very few memories carries little BM25 weight even though it is exactly what the user typed. artifact.keywordFields from memoryInspect shows what the lane actually indexed, per field.

Similarity. MemoryHit.similarityScore is on every hit that surfaced, and the trace carries the same figure for candidates that did not. Useful bands:

  • Above 0.80 — strong match. If it did not surface at this level, the problem is ranking, not retrieval: it was found and out-competed. Look at where fusion placed it.
  • 0.70–0.80 — moderate. Surfaces or not depending on competition. In a dense space, 0.75 can rank outside the band; in a sparse one it surfaces easily.
  • 0.60–0.70 — weak. Surfaces only when competition is thin.
  • Below 0.60 — the semantic lane treats it as unrelated. Correct when it is; a vocabulary gap when the memory and the query mean the same thing in different words.

Lexical score. Zero means no query term appears in the text after stemming and stop-word removal. Zero and a low similarity is the clearest signature of a vocabulary gap. A high lexical score with low similarity usually means the text contains the query's words while meaning something else — the lanes disagreeing is hybrid retrieval working, not failing.

Fusion. Ranks are fused with Reciprocal Rank Fusion, and the trace reports the k it used; brain_query_fusion_k exposes the same value as a metric. RRF scores a memory on its rank within each lane that found it, so breadth compounds: something ranked in the top ten by three lanes beats something ranked first by one. That is why which lanes found it is the first thing to look at — a memory only the entity graph reaches is structurally easy to miss.

The cut. What drops a fused candidate is a relevance band, not a top-K truncation, and it is server-side policy. RecallInput is { query, maxResults, subject, scope, includeTrace } — there is no top_k, no min_similarity and no filter weights to pass. maxResults caps what comes back (1 to 1000); it does not loosen the band. So when a candidate is in the trace and not in answer.memories, the client-side levers are maxResults, widening to scope: "namespace", or changing the memory's text — not a threshold on the call.

The filter chain. The trace names the filter that excluded a candidate. Confidence and salience are the two that bite, and both are readable per hit (confidence, salience) and settable as floors on the wire tier's cue — RecallBuilder.confidence(threshold) and .salience(floor). Supersession is the other common one: a statement that has been superseded is not current, and statementHistory shows you what replaced it. There is no touchMemory verb to refresh a memory's standing — MemoryListItem exposes lastAccessedAtUnixNanos and accessCount, which the engine maintains itself.

A scope exclusion should not occur: the credential determines the space, so there is no scope argument to mismatch between write and read. If a candidate is filtered on scope, the credential is not the one you think it is — check whoami().

Proactive health monitoring

Don't wait for user reports. Extraction errors, entity fragmentation, retrieval misses and confidence degradation are all measurable before they produce user-visible failures.

There is no health API to ask. No brain.health.deep(), no confidence_stats, no expected_miss_rate, no fragmentation_index, no estimated_junk_rate — none of those are computed anywhere. /healthz and /readyz answer "is the process up" and "is every shard serving", and that is the whole of what the engine will tell you about its health.

So the weekly check is a job you write, over reads that do exist:

async function weeklyMemoryHealthCheck() {
  const alerts: string[] = [];

  // Size and activity, per space. This is the stats surface.
  const { spaces, complete } = await brain.listSpaces();
  if (!complete) alerts.push("space listing was partial — treat counts as a floor");

  // Confidence distribution: computed from the statements, not read off a gauge.
  const { statements } = await brain.listStatements({ onlyCurrent: true, limit: 1000 });
  const mean = statements.reduce((a, st) => a + st.confidence, 0) / statements.length;
  if (mean < 0.55) {
    alerts.push(`Low mean confidence: ${mean.toFixed(3)} — extractor quality may have slipped`);
  }

  // Schema skew: are recent statements still being written against an old
  // version? There is no metric labelled by version, so read the field.
  const versions = new Set(statements.map((st) => st.schemaVersion));
  if (versions.size > 1) {
    alerts.push(`Mixed schema versions in current statements: ${[...versions].join(", ")}`);
  }

  // Thin memories: `entityCount === 0` means extraction found nothing to
  // anchor on, which is the closest real signal to "junk".
  let cursor: string | undefined;
  let thin = 0;
  let total = 0;
  do {
    const page = await brain.memoryList({ limit: 100, cursor, dir: "desc" });
    for (const m of page.items) {
      total++;
      if (m.entityCount === 0 && m.statementCount === 0) thin++;
    }
    cursor = page.nextCursor;
  } while (cursor && total < 1000);
  if (thin / total > 0.3) {
    alerts.push(`${((thin / total) * 100).toFixed(1)}% of recent memories derived nothing`);
  }

  return { healthy: alerts.length === 0, alerts, spaces };
}

Pair it with the two metrics that move first, which the engine does publish: brain_extractor_schema_filtered_total (claims the schema rejected — a spike means extraction and your types have drifted apart) and brain_extractor_resolver_outcome_total (entity resolution by outcome — the Ambiguous rate is the fragmentation signal, and an ambiguous resolution writes no link and logs nothing, so this counter is the only place it shows).

The point is not to act on every alert — some fluctuation is normal — but to catch trends before they compound. A thin-memory rate of 16% this week and 22% next week is worth investigating. A stable 8% is not.

These are your estimates, not Brain's

Everything above is a figure your job computes from a sample. Brain publishes no quality score, so there is no authoritative number to compare against and no threshold shipped with the product. Write the computation down beside the alert, because a number whose derivation is forgotten is a number nobody will trust when it fires.

Entity fragmentation deserves particular attention because it cascades: when the same person exists as two entity nodes, every relational query — find memories about X's manager, find all preferences X expressed — can return incomplete results. You detect it by listing entities and looking for near-duplicate names, and you fix it with mergeEntities (reversible via unmergeEntity). The Ambiguous outcome counter tells you it is happening; the entity listing tells you where.

Entity resolution debugging

When entity resolution fails the graph fragments, and relational queries return incomplete results. Detect it by listing entities and looking for near-duplicate canonical names.

One gotcha first: typeId is effectively required. The edge and gateway pass an omitted or 0 type through as "every type", and Brain rejects that with a 400 ("entity_type_id filter is required"). Pass a real type id or the call fails for a reason that reads like a bug.

const { entities } = await brain.listEntities({
  typeId: personTypeId,     // required in practice — see above
  mentionCountMin: 5,       // enough backing to be worth resolving
  limit: 1000,
});

// Suspected duplicates: similar canonical names, both well-attested.
const suspects: Array<{ a: EntityDetail; b: EntityDetail; score: number }> = [];
for (let i = 0; i < entities.length; i++) {
  for (let j = i + 1; j < entities.length; j++) {
    const score = nameSimilarity(entities[i]!.canonicalName, entities[j]!.canonicalName);
    if (score > 0.85) suspects.push({ a: entities[i]!, b: entities[j]!, score });
  }
}

mentionCountMin: 5 focuses on entities with enough backing to matter — mentionCount is on every EntityDetail. Entities with one or two mentions are often transient references the resolver correctly declined to attach to anything; don't merge those automatically.

Before merging, read both entities and the claims attached to each. Statements are keyed on the subject entity, so that is the listing to use — there is no listMemories({ filter: { subject_entity_id } }):

const a = await brain.listStatements({ subject: suspect.a.entityId, limit: 200 });
const b = await brain.listStatements({ subject: suspect.b.entityId, limit: 200 });

if (shouldMerge(a.statements, b.statements)) {
  // The survivor is the PATH id; the one folded in goes in the body.
  const { auditId, gracePeriodSeconds } = await brain.mergeEntities(
    suspect.a.entityId,
    {
      merged: suspect.b.entityId,
      confidence: 0.95,
      reason: "entity resolution failure: same person, two nodes",
    },
  );
  console.log(`merge ${auditId} reversible for ${gracePeriodSeconds}s`);
}

Three things the result tells you that matter operationally. The merge is reversible, but only for a window — gracePeriodSeconds, after which unmergeEntity no longer restores it. It carries an auditId, so the merge is recorded internally even though no verb reads those records back. And the call is single-shot, deliberately not retried: a merge writes an audit record, so a retried one writes a second. Do not wrap it in your own retry loop.

Afterwards the folded entity carries mergedInto pointing at the survivor, and getEntity on the old id redirects — the result's redirect chain is non-empty when the row you got back is not the one you asked for, which is the signal to check before treating an id as canonical. Pass includeMerged: true to listEntities to see folded-away entities at all; they are hidden by default.

Verify by re-running the relational read against the survivor and checking the statement count rose by what you expected.

When not to merge: two similar names that are genuinely different people — two people called Alex on one team. The resolver was right to keep them apart. Give each more signal instead, via updateEntity on canonicalName and aliases. But read the entity first: updateEntity is a wholesale replace, so an omitted aliases or attributes clears it, and an update that only meant to change a name wipes attributes the caller never saw. getEntity returns both so a read-modify-write round-trips.

Space isolation debugging

A common production fear: memories from one user appearing in another's context. The reassuring part is that Brain's isolation does not depend on your application getting a parameter right.

There is no scope field on a memory and no provenance.source_scope to compare against. There is also no I-5 invariant to rely on — that check does not exist. What exists is stronger: the space, and a credential is scoped to one. A caller reading its own space cannot address another, because there is no scope argument on recall or encode to be wrong. Cross-space reads happen only through scope: "namespace" on a recall, which is explicit and auditable in your own code.

So the failure mode the original of this section described — a write arriving with the wrong user id — becomes a different and simpler question: was the write made with the wrong credential, or under the wrong actAs identity?

// What can this credential actually see? Ask, rather than assuming.
const { namespace, spaceId, permissions } = await brain.whoami();

// Does the space hold what you expect it to?
const { spaces, complete } = await brain.listSpaces();
if (!complete) {
  // The listing covered only the caller's shard. Treat it as partial —
  // concluding a space is absent from an incomplete listing is the mistake
  // this flag exists to prevent.
}

If a memory is in the wrong space, it was written there — by a credential for that space, or by an actAs(namespace, space) naming it. The space is fixed at write time and cannot be changed afterwards: there is no move operation. The only remediation is to forget it where it is and re-encode it where it belongs.

// Per memory. `forget` takes a memoryId and an optional `hard` — there is no
// scope argument and no `reason` field to record why.
await brain.forget({ memoryId, hard: true });

// Then re-encode under the right identity.
await brain.encode(
  new EncodeBuilder(text).actAs(namespace, correctSpace).build(),
);

Note what you will not get from Brain while investigating: there is no audit entry naming the credential that wrote a memory, and no actor recorded on the original insert. Finding which component wrote into the wrong space is a job for your own request logs, which is a reason to log the (credential, space, memoryId) triple at write time.

The usual causes are unchanged: a session id reused across user contexts in a multi-tenant setup, a middleware layer mapping sessions to the wrong tenant after a handoff, and migrations that re-encode into a space chosen once at the top of a loop.

Scope violations are a data privacy issue

A memory from user A appearing in user B's context is not just a correctness problem — it is a potential data privacy incident. Treat scope violations with the same urgency as any other personal data exposure. Quarantine first, investigate second. Document the scope of exposure (which users were affected, for what time window) so you can assess notification obligations under your applicable data privacy requirements.

Hallucination investigation workflow

When a user reports that the agent said something false that appeared to be grounded in memory, the investigation workflow follows a consistent pattern. The goal is to determine whether the false claim came from a wrong memory (an extraction failure) or from the model going beyond what the memory actually said (a faithfulness failure). The two cases have different root causes and different fixes.

Step 1: Get the response that contained the false claim and the retrieval context that was injected into the prompt. The retrieval context should include memory IDs — if your prompt template doesn't currently include them, add them. They are essential for this kind of investigation. Identify which memory IDs were cited by the response.

Step 2: Inspect what was cited:

const cited = await Promise.all(
  citedMemoryIds.map((id) => brain.memoryInspect(id)),
);

for (const { memoryId, text, artifact } of cited) {
  console.log({
    memoryId,
    text,                                  // what Brain actually stores
    kind: artifact.record?.kind,
    salience: artifact.record?.salience,
    occurredAt: artifact.record?.occurredAtUnixNanos,
    derivedGraph: artifact.graph?.edges,    // what the extractor concluded
  });
}

memoryInspect, not getMemory — and there are no source_turn_ids and no extracted_by.model to print. The memory's text is what you sent; the extractor's reading of it is artifact.graph. Confidence is not on the memory either: it is on the derived statement, so for the claim behind the answer read listStatements({ subject, predicate }) and look at confidence, extractorId and extractedAtUnixNanos.

Step 3: Check whether the stored content actually supports the claim. Two distinct failure modes:

Case A — the memory is correct and the model went beyond it. The memory says "user works at Volkswagen"; the agent said "user is the CEO of Volkswagen." That is a faithfulness failure in your prompt, not a memory problem. Add an explicit constraint — cite exactly what the memory states; do not infer roles, relationships or attributes beyond what is recorded — and evaluate it across a representative sample before shipping, because an over-strict instruction makes the agent less useful where reasonable inference is appropriate.

Case B — the stored claim is itself wrong. Here the honest limit matters: you cannot trace it to the source turn, because Brain does not store turns and keeps no link to them. What you can do is read artifact.graph to see whether the extractor over-generalised from the text it was given — if the text says "I had a call with the Volkswagen team today" and the derived edge asserts a ceo_of relation, the over-reach is visible right there. Then correct it:

// Claims are superseded, not edited — the wrong revision stays readable.
await brain.supersedeStatement(wrongStatementId, {
  kind: "fact",
  subject: userEntityId,
  predicate: "works_at",
  object: { entity: volkswagenEntityId },
  confidence: 1.0,
  evidence: [sourceMemoryId],
});

// If the memory's TEXT is the problem, there is no edit. A memory is
// immutable once written: forget it and encode the corrected text.
await brain.forget({ memoryId: wrongMemoryId, hard: true });

Step 4: Ask why the wrong one ranked where it did — with a traced recall, since there is no debugRetrieval and no top_k_to_inspect:

const answer = await brain.recall({
  query: "what is the user's role at Volkswagen?",
  maxResults: 10,
  includeTrace: true,
});
// answer.memories carries similarityScore, confidence and salience per hit;
// the parsed trace shows every candidate each lane considered, so a correct
// memory sitting below the wrong one is visible there.

If a correct memory exists but ranked lower, it is ranking competition. The wrong one may carry higher salience, or match the query's wording more closely — note that a hit's confidence is a property of the record, not evidence that the claim is true, which is exactly how a confidently-wrong extraction out-ranks a correct one. After correcting or forgetting it, re-run the recall and confirm the right memory surfaces.

Common extraction error patterns and fixes

Four patterns worth recognising. Each one is detectable — but from the derived graph and the typed statements, not from provenance fields that do not exist. There is no source_turn_ids to inspect and no trace to open, so the signature in each case is something the engine actually returns.

Over-extraction of agent statements. The extractor takes facts from the assistant's own turn rather than the user's. An assistant saying "I understand that you work at Volkswagen" yields "user works at Volkswagen" — sourced from a restatement, not an assertion. You cannot see which speaker it came from, because Brain stores the text you sent and nothing about its origin. So the fix is on your side of the call: send user turns, or send a speaker-labelled text and instruct extraction accordingly. What you send is what gets extracted from; there is no extract_from_assistant switch, because there is no notion of an assistant turn in the first place.

Pronoun resolution to the wrong entity. A claim is attributed to the wrong entity because "she" or "they" resolved to someone else. The signature is in the derived graph, which is readable:

const { text, artifact } = await brain.memoryInspect(memoryId);

// The extractor's own nodes and edges, with the confidence it assigned.
artifact.graph?.nodes;   // [{ id, name, kind, typeQname }]
artifact.graph?.edges;   // [{ source, target, predicate, kind, confidence }]

If an edge's source or target is an entity whose name does not appear in text, the resolution reached outside the memory. The aggregate signal is brain_extractor_resolver_outcome_total, broken down by outcome — an Ambiguous resolution writes no link at all, which is the quiet version of the same failure. Remediation for entities already fragmented this way is mergeEntities.

Temporal anchor mismatch. An event's time is the write time rather than when it happened. "I had a great meeting yesterday" lands as today. This one is entirely in your control and has a real parameter: occurredAtUnixNanos on encode (occurredAt on EncodeBuilder). Omit it and Brain uses record time for both, which is why a year of back-filled history all appears to have happened at import. The signature is a statement whose eventAtUnixNanos equals its extractedAtUnixNanos — both are on StatementDetail, so this is a check you can run:

const { statements } = await brain.listStatements({ kind: "event", limit: 500 });
const suspect = statements.filter(
  (st) => st.eventAtUnixNanos === st.extractedAtUnixNanos,
);

Confidence inflation from corroboration. Repeated hedged mentions produce a high-confidence claim — "I usually prefer async" across three sessions becoming confidence: 0.97 when every source was qualified. High confidence survives the filter chain and ranks well, so a confidently-hedged claim suppresses a directly-stated one. It is a calibration issue rather than a bug, and the place to see it is the revision chain: statementHistory shows each revision's confidence alongside its extractedAtUnixNanos, so a claim whose confidence climbed across revisions without the wording getting firmer is visible. Watch brain_extractor_predicate_consolidated_total for the aggregate.

The common thread: every one of these is found in the derived graph or in the statements, and corrected by superseding a claim or by changing what you send. None of them is found in an audit log or a pipeline trace, because neither exists — and the two that are genuinely your responsibility, speaker selection and occurredAtUnixNanos, are decided before the write rather than diagnosed after it.

All Engineering Posts

Updates from the lab.

Engineering notes, research drops, occasional product updates. Roughly monthly.

Arc Labs

Cognitive infrastructure for AI agents. Open core in Rust. Composable primitives you own.

GitHubX / TwitterDiscussions

Brain

  • Memory Layer
  • Documentation
  • Pricing
  • Changelog
  • Status

Developers

  • Start here
  • TypeScript SDK
  • Python SDK
  • Rust SDK
  • MCP Server

Company

  • About
  • Careers
  • Blog
  • Security
  • Contact
Encode"Priya lives in Berlin."mem_7f3a · storedRecall"where does Priya live?"→ BerlinSupersede"Priya moved to Lisbon."mem_9c21 ⊃ mem_7f3aBerlin→ LisbonARC LABSARC LABSARC LABS
© 2026 ARC LABS · BANGALOREPrivacyTermsDPAApache 2.0