---
title: Agentic memory
description: Learn how agentic memory works, when to use working or long-term memory, and how agent memory and document RAG work together.
seo:
  title: What is agentic memory?
lastModified: '2026-11-28T13:36:41.000Z'
---

<a id="memory"></a>

Agentic memory lets an AI agent store, retrieve and revise information as it works.
It keeps selected facts, past actions and procedures available across sessions and
runs. The agent or application decides what to save and which parts to bring into
the model's context for the current request.

A memory is one claim an agent should find again: "deploys happen on Tuesdays", "the
payments team owns the billing service". Loom stores each claim as a row in
`loom.memory`, under a readable key, with who wrote it, when it was true, where it came
from and whether anyone vouched for it. This page covers the row, how a write is judged
against what is stored, and how rows change over time.
[Retrieval and ranking](/docs/concepts/retrieval-and-ranking) covers how rows are found.

## Working memory and long-term memory

The context window holds the input supplied to the model for one request.
[Working memory](/docs/features/memory/working-memory-and-profiles#working-memory)
holds small pieces of task state, such as a cursor or the checks already completed.
A replacement process can read the block again with the same identity and run ID.
Long-term memory carries reusable information across runs. It can include facts,
past events and procedures for recurring tasks. See [memory types](#memory-types)
for how Loom stores each one.

For a support agent processing a return, put the order and completed checks in
working memory. Save a reviewed refund rule as a short claim and link it to the
[source policy](/docs/features/knowledge#how-do-agents-connect-a-memory-to-a-source-document).
A later session can retrieve the rule within its authorized namespace. When the
policy changes, [review the source and correct the saved claim](/docs/use-cases/knowledge-factory#check-the-lesson-after-a-runbook-change)
so readers can see which version they used.

## How agent memory and RAG work together

Retrieval-augmented generation (RAG) brings retrieved evidence into the model's
input before it generates an answer. Agent memory keeps selected facts, decisions
and procedures available across runs. An agent can retrieve memories, documents,
or both before it answers.

For a return, retrieve the current approved policy to find the refund window and
cite the document revision. Retrieve a saved lesson to find how the team handled
an earlier exception. Use the policy for the rule and the lesson as evidence about
that case. If the lesson and the current policy disagree, check the cited passage
and send the lesson for review before reusing it.

In Loom, [document search](/docs/use-cases/document-search) returns passages and
their source citations. [Memory search](/docs/features/memory/search-and-ask)
retrieves saved claims. When a claim comes from a policy, [link it to the source
document](/docs/features/knowledge#how-do-agents-connect-a-memory-to-a-source-document)
so a later reader can verify the evidence.

## How to tell whether an agent used a memory

Suppose the agent retrieves an earlier refund exception while processing a return.
Check which evidence the agent applied to the current order.

1. **Check what the model received.** Record the memory keys returned by search and
   compare them with the evidence your application passes to the model.
2. **Check what the agent relied on.** Inspect the answer or action for the rule the
   agent applied to the order. [Run history](/docs/features/runs#recalled-is-not-relied-on)
   separates recalled keys from `memories_used`, which records what the agent reports using.
3. **Check the outcome.** Grade the decision against the approved policy. To measure
   the effect of memory, [compare runs with and without saved lessons](/docs/getting-started/evaluate#compare-coding-agents-with-and-without-memory)
   using the same model, tools, policy revision, and acceptance criteria.

## Rows in ClickHouse

Memories, document chunks, conversation turns, entity edges, code symbols, runs, audit
entries and erasure requests are all rows in ClickHouse, created by numbered migrations
the server applies on boot. Under the
[Postgres memory authority](/docs/architecture/storage-authority#why-two-stores),
Postgres holds live memory and knowledge state, and ClickHouse keeps the vectors, search
and history. Uploaded document originals are ClickHouse rows too
(`loom.document_blobs`), unless the deployment keeps their bytes in an S3-compatible
bucket. Outside ClickHouse, Postgres and that bucket, Loom keeps the code index's git
mirrors, a cache of the remotes ClickHouse records, and the rate-limit buckets on a
shared volume.

- **The identity tuple leads the sort keys.** `loom.memory` is ordered by
  `(org, namespace, agent, user_id, session_id, memory_key)`, so scoping a read to a
  namespace is a primary-key range; a user narrows it fully only under a named agent,
  a session only under a named agent and user.
  [Identities and namespaces](/docs/concepts/identities-and-namespaces) covers the tuple.
- **One engine.** Under the default ClickHouse authority, vector search, lexical search,
  the graph walk, filters, audit and erasure are SQL over the same rows, with no second
  store to keep in step. The cost is that every read is a query, not a key-value hit.
  Under the Postgres authority, point reads (by key or id, outside an `as_of` replay)
  are answered from Postgres.
- **A write is a new version.** The memory tables are `ReplacingMergeTree(version)` read
  with `FINAL`. A revision, tombstone, pin or restore inserts a new version row.

## The write, derive, read loop

```mermaid
flowchart LR
    W["Writer: memory.set,<br/>set_from_messages,<br/>knowledge.add"] --> G["Write checks:<br/>lock, pin, blacklist,<br/>precondition, conflict"]
    G --> T[("ClickHouse rows:<br/>memory, embeddings,<br/>chunks, audit_log")]
    T --> D["Workers derive:<br/>entities, deferred extraction,<br/>consolidation, calibration,<br/>usage folds"]
    D --> T
    R["Reader: memory.search,<br/>memory.ask, context.pack"] --> L["Retrieval legs:<br/>vector, lexical, graph,<br/>chunks, digests"]
    T --> L
    L --> K["Fuse and rank,<br/>gate or abstain"]
    K --> A["Answer with provenance"]
    A --> F["run.complete,<br/>memory.outcome"]
    F --> T
```

1. **Write.** `memory.set` runs its checks ([below](#how-a-write-is-judged)), embeds the
   value inline, and inserts the memory row, its embedding row, verbatim chunks for long
   values and a hash-only audit row. If the inline embed fails, the call fails and nothing
   is written.
   `memory.set_from_messages` has the LLM pick the durable facts in a transcript and
   writes through the same bulk path.
2. **Derive.** Workers add what is too slow for the write path: entity tags
   (`entity_extractor`), deferred extraction (`extraction_queue`), consolidated facts,
   gate recalibration, and usage folded into ranking signals (`usage_fold`). Derived rows
   carry `source_class=derived`.
3. **Read.** `memory.search` runs several legs (vector, lexical, entity graph, verbatim
   chunks, session digests), fuses them, ranks, and returns hits or abstains.
   `memory.ask` writes a grounded answer; `context.pack` builds a budgeted prompt block.
4. **Feed back.** A run that names the memories it relied on (`run.complete`
   `memories_used`, or `memory.outcome`) credits them; a bad outcome records harm. This
   becomes a bounded, decaying ranking term. It never deletes a row or ranks it below
   its relevance.

The loop is eventually consistent. A read right after a write finds the fact through its
inline embedding; entities and extracted facts arrive after the worker's next pass.

## The `loom.memory` row

One row is one version of one memory.

| Group      | Columns                                                                         | Decides                                                       |
| ---------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| Identity   | `org`, `namespace`, `agent`, `user_id`, `session_id`, `run_id`                  | Who may read it and who wrote it                              |
| Address    | `memory_key`, `memory_id`                                                       | How a caller names it (key) and how Loom names one row (id)   |
| Content    | `value`, `memory_type`, `tags`, `entities`, `files`, `confidence`               | What it says and how it is classified                         |
| Lifecycle  | `status`, `pinned`, `conflict_with`, `duplicate_of`, `superseded_by`, `version` | Whether it is served, and what replaced it                    |
| Time       | `created_at`, `updated_at`, `valid_at`, `valid_to`, `invalid_at`, `expires_at`  | When it was written, when it was true, when it left service   |
| Provenance | `actor`, `source_class`, `content_sha256`, `verified_by`, `verified_sha256`     | Who wrote it, how Loom learned it, whether anyone attested it |
| Guards     | `lock_mode`, `lock_until`, `sensitivity`, `on_expire`                           | Which writes it refuses and how it is read                    |

The full column list is in the [schema reference](/docs/reference/schema). A searchable
memory also has a row in `loom.memory_embeddings`: vectors for the value and the key,
lowercased, stemmed and lemmatised copies of the excerpt for lexical matching, and the
`source_class` and `verified` flags the ranker reads.

## Keys

A key names one attribute of one subject, as a readable path `<scope>/<kind>/<id>`:

```
sre/case/1234/evidence/dns-sidecar
project/loom/deploy-window
user/preferences/editor
```

- **One fact per key.** Conflict checks, supersession and history work per key. A key
  holding a list of unrelated facts cannot be partly revised.
- **A revision rewrites the same key.** Loom keeps every version, so a numbered copy
  (`…-v2`) or a key made from a hash of the value only hides the revision. Hash-made
  keys are the `hash_keys` finding of `namespace.audit`.
- **Facets go in `tags` and `entities`,** not in the key.

The storage identity is `(org, namespace, agent, user_id, session_id, memory_key)`: the
same key written by two agents or in two sessions is two rows. Under the namespace
policy `newest_wins`, the newest write for a key retires every older live row with that
key in the namespace, whoever wrote it. Extraction mints keys from the subject and
attribute, never from the value, so a later session that states the same attribute lands
on the same key. Under `auto_reinforce` and `manual_review`, the conflict resolver judges
the rows of one key that two sessions of the same user (not the anonymous user `-` or a
user_id sent empty, whose sessions are separate tasks) wrote, from a point write or a bulk
write, as it judges any close pair: it retires the older row of an update it is sure of
(except under `manual_review`), flags a contradiction for review and leaves two different
facts under a reused key live. Under `append_only` nothing is judged.

## Memory types

`memory_type` is a free string, default `semantic`. A few values change how the row is
stored and found (`server/memory/domain/memory_types.py`):

| Type                   | Embedded | In unfiltered search | Use for                                                  |
| ---------------------- | -------- | -------------------- | -------------------------------------------------------- |
| `semantic` (default)   | yes      | yes                  | Durable facts.                                           |
| `preference`           | yes      | yes                  | Preferences that should rank in recall.                  |
| `procedural`           | yes      | yes                  | Procedures (`procedure.*`).                              |
| `reflection`           | yes      | no                   | Lessons from runs; read with `memory_type="reflection"`. |
| `episodic`             | no       | no                   | Session events replayed by recency.                      |
| `profile`              | no       | no                   | Always-loaded context fetched by label (`profile.*`).    |
| any other (`decision`) | yes      | yes                  | Domain types are searchable by default.                  |

- **Reflections are hidden** from unfiltered search and `memory.ask`: a lesson about a
  process is not a claim about the world.
- **A `procedural` write** whose value is not a procedure body (a non-empty `situation`
  and at least two `steps`) is stored as `semantic`, tagged `retyped_from:procedural`,
  and the response says so in `retyped_from`.
- **Sensitivity.** A row with `sensitivity="high"` is never embedded, so no search leg
  finds it. It is readable by key only, and that read is audited. With `sensitivity`
  unset the server detects credential shapes, card numbers, US Social Security
  numbers and stated PINs (`high`), and email, phone and IBAN shapes (`medium`)
  (`LOOM_MEMORY_SENSITIVITY_AUTODETECT`).

## Status

| Status       | Meaning                                                                    | Served by default         |
| ------------ | -------------------------------------------------------------------------- | ------------------------- |
| `active`     | The live belief.                                                           | yes                       |
| `conflicted` | Close to a peer but saying something different; linked by `conflict_with`. | yes                       |
| `duplicate`  | Near-identical to a canonical row (`duplicate_of`), which answers for it.  | no (`include_duplicates`) |
| `superseded` | A later row replaced it (`superseded_by`, retired at `invalid_at`).        | no (`include_superseded`) |
| `proposed`   | A fact on trial, decided with `memory.proposal_decide`.                    | no (`include_proposed`)   |
| `rejected`   | Marked wrong (`memory.reject`, or a rejected proposal).                    | no                        |
| `tombstoned` | Deleted by its writer (`memory.delete`).                                   | no                        |

The served set is defined once, in `server/memory/domain/temporal_sql.py` (`SERVED_STATUSES`). A
conflicted row stays served: hiding one side of a contradiction would let the store
answer confidently with a fact it has reason to doubt.

## How a write is judged

Five operations cover the memory lifecycle:

| Lens      | Operation             | Effect                                                              |
| --------- | --------------------- | ------------------------------------------------------------------- |
| Expand    | `memory.set`          | Learn a fact under a key.                                           |
| Revise    | `memory.update_by_id` | Correct one row by id (`memory.update` does the same by key).       |
| Contract  | `memory.delete`       | Tombstone a key and refuse later intake of its removed value.       |
| Reinforce | `memory.pin`          | Store and pin: no later write that does not itself pin replaces it. |
| Refuse    | `blacklist.add`       | Refuse every future write matching a substring or regex.            |

A searchable `memory.set` runs these checks in order:

1. **Lock and pin guards** on the row under the key. `memory.lock` (`read_only` or
   `no_delete`) answers 423 `LOCKED`. A changed value under a pinned key is 409
   `PINNED_CONFLICT`. A byte-identical restatement passes every guard.
2. **Blacklist.** A value matching a registered pattern is 422 `BLACKLISTED`; in a bulk
   write the entry is skipped. Replicas cache patterns and poll a one-row version table
   (`loom.blacklist_version`), so a new pattern reaches every replica within seconds.
3. **Precondition.** `if_match_sha256` makes the write land only if the live row's hash
   still matches; otherwise 409 `PRECONDITION_FAILED`. The current hash rides every
   `memory.get`, `memory.get_by_id` and `memory.set` response (`content_sha256`).
4. **Restatement.** A value byte-identical to the live row writes a new version that
   carries the live row's `reinforcement_count + 1`. The bulk path (`memory.bulk_set`,
   used by `set_from_messages`) treats any live row with the same hash in
   `(org, namespace, agent, user_id)` as the fact (`LOOM_MEMORY_BULK_DEDUP_SCOPE=identity`).
5. **Peer search and verdict.** Active rows of the same `memory_type` whose embedding is
   close to the new value are **peers**, compared closest first; a write that names its
   `user_id` takes them from that user's rows only
   ([how a write is judged](/docs/features/memory/conflicts-and-refusal#how-a-write-is-judged)):
   - same canonical form (lowercased, punctuation stripped, whitespace collapsed) →
     `merge`: nothing written, the peer is reinforced, `merged_into_key` names it;
   - a close pinned peer → `rejected`, 409 `PINNED_CONFLICT` (under a namespace-wide
     token, a write that names its user and restates another user's or a shared pinned
     value is written);
   - under `newest_wins`, a peer that states the same subject and predicate with a
     different object → `refines`: the peer is retired, unless its `valid_at` is later
     than the new row's, which answers `conflict`;
   - cosine at or above the duplicate threshold with the same content words and no
     differing value (a number, time, amount or unit; "27:10" / "26:30") →
     `duplicate`;
   - cosine at or above the conflict threshold but different → `conflict`, both rows
     `conflicted`;
   - no close peer → `clear`.
6. **Insert** into `loom.memory` and `loom.memory_embeddings`, supersession, entity
   projection and one hash-only row in `loom.audit_log`.

A non-searchable type or a `high`-sensitivity row skips the peer search: it has no
embedding to compare. `dry_run=true` runs every check and writes nothing, which answers
"new fact, restatement or contradiction?" before you commit to a key. The response
carries `conflict_verdict`, up to five `peers`, and a `next` hint.

- **Thresholds.** With `LOOM_ADAPTIVE_THRESHOLDS` on and a real embedder, the conflict
  and duplicate thresholds come from the embedder's own similarity distribution at boot
  (`server/memory/app/embedder_calibration.py`). The scalars `LOOM_CONFLICT_THRESHOLD`
  (0.85) and `LOOM_DUPLICATE_THRESHOLD` (0.97) are the fallback. A namespace or memory
  type can pin its own; `calibration.get` reports which is in force.
- **The conflict resolver.** Cosine says two statements are about the same thing, not
  whether they agree. A leader-only worker judges each write with a close peer after it
  lands, one LLM call per row: it retires the older row of an update it is sure of under
  the default `auto_reinforce` and under `newest_wins` (the old value stays readable
  with `include_superseded` and `as_of`), flags a contradiction, and clears a false flag
  ([conflicts](/docs/features/memory/conflicts-and-refusal#the-conflict-resolver)). No
  verdict on the write itself calls an LLM.
- **Run scope.** A write under a `run_id` whose canonical match belongs to another run is
  stored as a `duplicate`, not merged, so a run-scoped read still finds it.
- **Namespace policy.** `default_conflict_policy` decides what a contradiction does
  (`auto_reinforce`, `manual_review`, `newest_wins`, `append_only`).

`memory.update`, `memory.update_by_id` and `memory.bulk_set` run the same check. Verdict
details, the policies, the Review queue and `conflicts.resolve` are in
[conflicts and refusal](/docs/features/memory/conflicts-and-refusal).

**Pins protect what the user said.** A pinned row is never replaced by a write that does
not itself pin, by key or by a close value under another key. To change it, use
`memory.update` (keeps the pin) or `memory.pin` (re-pins). `memory.for_file` lists
pinned rows first; no other read orders by the pin.

**Consolidation keeps lineage.** `memory.consolidate` (and the consolidation worker, when
a namespace opts in) merges fragments about one subject into canonical rows with
`source_class='derived'`, and writes one `loom.memory_belief_sources` row per source
(`support_type='derived_from'`). Deleting a source retires a consolidated row when none
of its sources survive, and downgrades it to `conflicted` when some do
(`dependents_tombstoned`, `dependents_downgraded` in the `memory.delete` response).

### A memory's lifecycle

```mermaid
stateDiagram-v2
    [*] --> active: memory.set (clear, refines)
    [*] --> conflicted: memory.set (conflict)
    [*] --> duplicate: memory.set (duplicate)
    [*] --> proposed: memory.set(proposed=true)
    active --> conflicted: a later close write
    conflicted --> active: conflicts.resolve (revise, allow)
    conflicted --> tombstoned: conflicts.resolve (contract, or peer revised)
    proposed --> active: memory.proposal_decide (accept)
    proposed --> conflicted: memory.proposal_decide (accept, contradicted on trial)
    proposed --> rejected: memory.proposal_decide (reject)
    active --> rejected: memory.reject
    active --> superseded: newer write (newest_wins, refines, conflict resolver)
    superseded --> active: memory.restore
    active --> tombstoned: memory.delete, blacklist sweep, expiry
    tombstoned --> active: memory.restore (automatic retirement, no refusal)
```

Every arrow is a new version; the old one stays in `loom.memory_versions`.

## Tags, entities and files

- `tags` are free labels (`case:1234`, `kind:evidence`). A search filters on them
  (`tags`), boosts with them (`tags_soft`), or sinks them (`demote_tags`). A namespace's
  `tag_registry` can attach retention, dedup and conflict policy to a tag. Tags keep the
  case they were written in: `memory.list` and `knowledge.list` match them in any case,
  and every other tag filter, `memory.search` and `memory.apply` included, matches them
  exactly.
- `entities` are the named things the value mentions, stored in the canonical form search
  reads them in (lowercased; articles, possessives and punctuation dropped; the head noun
  singular), so `Billing Services` and `billing service` are one entity. A writer may pass
  them; otherwise the `entity_extractor` worker fills them. They drive the entity boost
  and the [entity graph](/docs/features/entity-graph).
- `files` are repository paths the memory is about; `memory.for_file` serves them before
  an edit of those files.

`memory.for_file` renders one line per memory. A decision or a constraint prints whole,
up to the ceiling below, and does not count against the request's `token_budget` (300
tokens by default); the other rows are held to it, cut to one line of 220 characters. A
row that does not fit is left out whole while the rows after it still get their turn,
and a closing `- … <n> more` line, which counts against the budget too, says how many
were left out and how to list them. The header and the removal footer are always
printed, and the `… more` line whenever a row is left out, so a budget smaller than those
can be exceeded.

Decisions and constraints share one ceiling, `memory_for_file_whole_tokens` (1,500
tokens, about 6,000 characters), so a file governed by dozens of them cannot flood the
prompt. They print in the block's order; one that would pass the ceiling is left out,
and the ones after it that still fit print. A closing line counts those left out and
names the first five keys, each read with `memory.get` (in the namespace it names, for a
team row) or found with `loom_search`. A row left out with the newer row that supersedes
it is counted on the `… more` line instead, never named as one to read. The default
keeps the whole block under the 10,000 characters a coding-agent host passes from a hook
to the model as it is.

Each line:

- A memory from an extra namespace (the repository's code namespace) is headed
  `Team rule (by <author>, <age>)`, or `Decision (by <author>, <age>)` for a decision
  (`memory_type` `decision` or the tag `decision`).
- A line lists its `constraint`, `gotcha` and `decision` kinds in one bracket
  (`[constraint, decision]`; a line headed `Decision` leaves out `decision`).
- `(pinned)` marks a pinned row. A pin is the row's own flag: a member of a code namespace
  can set it on a row they write there, so `(pinned)` on a team row says someone froze it,
  not that a maintainer did.
- A decision nobody pinned, such as one `loom decisions extract` wrote, carries no pin
  mark: it is served as it is.
- `(outcome: failed)` marks any decision whose recorded outcome failed, pinned or not.
- A decision tagged `source-changed` (its source document no longer says it; see
  [extracting decisions](/docs/features/tasks-and-decisions#extract-decisions-from-a-document))
  reads `(source changed)`, pinned or not.
- A note says when its linked code changed or went.
- A string value is printed as text, not as the JSON it is stored as, and a row other
  than a decision or constraint ends in `…` when the read or the line cut it; a cut
  object or list prints as stored.
- A decision with a source carries ` — source: <source_resource_id>` after its value,
  whole, so a `knowledge:` citation keeps its `#section` and resolves through
  `knowledge.get`.
- A newer row the conflict check linked to an older one of its type is placed above it,
  and a team line says which it supersedes (`supersedes decision` when the older is tagged
  `decision`). Two typed decisions the check linked each keep their place in the block,
  with no such note, since each decision key is its own decision. When the budget or the
  ceiling leaves out any row that supersedes others, in any namespace, every row it
  supersedes is left out with it, so an older row never reads as current.

## Memories linked to code

What this gives a coding agent, and where to start:
[memory linked to code](/docs/use-cases/memory-linked-to-code).

A memory about code is linked to the definitions and files it names, and the links
follow the code. The `memory_code_links` worker links each memory tagged `repo:<id>`
(the coding plugins tag their sessions) or written in a repository's code namespace
against that repository's trunk:

- each backticked name, `A::b` and `a.b()` call that resolves to exactly one definition;
  the memory's `files` pick between namesakes, and a name defined more than once is not
  linked;
- a bare camelCase or snake_case word of the prose only to a definition in the memory's
  `files`;
- each file the memory names that holds none of those definitions.

The worker checks pending names in pages and links them when it finds their definitions
on trunk. It drops names older than `memory_code_links_pending_days` (14 by default),
measured when the scan starts.

A memory whose key starts with `obs:` is a raw tool observation (`observe.record` keys a
tool call's row `obs:<session_id>:<sha8>`) and is never linked: it records a tool call, not
a lesson, though a coding plugin's carries its session's `repo:` tag and quotes the code a
tool read.

A link records the definition's fingerprint: all its overloads and the conditions that
select them, as tokens, so whitespace, comments (not a Go `//go:` directive or a Python
`# type:` comment) and most of what formatters change (trailing commas and other optional
separators, a JavaScript `;`, quote style and the escapes it needs, the case of a number
literal, a Python docstring's indentation, parentheses in Python, JavaScript and
TypeScript) leave it as it was. Joining adjacent string literals, and any other edit, does
not.
What a file defines is read from the file at the repository's indexed head in its bare
git mirror. On every indexed commit the worker follows the commit's renames and edits, and
a [`code.refresh`](/docs/features/code-index/freshness#pushing-freshness-from-ci) call
follows them as soon as its ingest pass ends:

| Link state   | When                                                                                                               |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| `fresh`      | The definition is where it was, with the text the memory was written against.                                      |
| `moved`      | Its file moved, or it was renamed with nothing else changed, or it moved to another file.                          |
| `changed`    | Its text changed after the memory was written (`changed_since` names the commit), renamed or not.                  |
| `unresolved` | Its name is gone and a new definition in its place may be it, but none certainly is. Served, with a review signal. |
| `missing`    | The code is gone: nothing new took its place. The link keeps its place, so a revert finds it again.                |

A link to a file follows the lines of that file that hold a name the memory cites: the
last part of each name above, of four or more characters, as a whole word. A name on
more than eight lines of the file (`None`, `self`) is a word of that file and is not
followed. The link reads `changed` when the cited lines are no longer the ones the memory
was written against, and `fresh` again once they are back. An edit to a line that holds
none of those names, a shift of the cited lines or a new indentation leaves it `fresh`,
so a memory about a long file is not marked by every commit to it, and a memory that
cites no name in the file (a rule about the file as a whole) is marked only when the file
moves or goes. An edit that takes a name across eight lines changes which lines are
followed, and marks the link. A link written against no cited line takes the first ones a
later commit brings as the lines it was written against. When a commit defines a name the
memory gives in the file (the memory was written before its function merged), a link to
that definition, written against its text at that commit, replaces the file link. A name
the memory already has a link for keeps that link: a commit never moves a link to a
namesake. `revise` does not re-check a file link: a changed one is flagged.

![A memory's detail in the dashboard: its linked code, one definition current and one changed since a commit](/docs/blume-assets/content/.blume-content/assets/screenshots/memory-linked-code.webp)

A memory's detail in the dashboard lists these links with their state
([clip](/docs/blume-assets/content/.blume-content/assets/screenshots/clip-memory-linked-code.webm)).

A link follows its definition through file moves, renames (with an edit, when the new
name is related to the old), and its class's rename within the file. A definition renamed
as it moves to another file, class or namespace is looked for among the definitions the
changed files did not have before, by three rules in turn:

1. The only one with its tokens under another name reads `moved`. It is looked for before
   a definition of its own name with an edit in another file, and whatever the search of
   its own file left unsure.
2. The only one of its own name with a close text reads `changed`, unless a definition of
   that name that stayed in the changed files is close as well.
3. The only one whose text is nearly its own under any name, a tenth of its tokens
   differing at most (a parameter, a callee renamed with it), reads `changed`, when no
   other removed definition is as near to that one and no definition that stayed is as
   near to it.

Rules 2 and 3 apply only when the search of its own file left no new definition there
that may be it. A member reads `changed` there unless its class came with it unchanged.
Two definitions that may be it, or one that another removed definition may have become,
leave the link `unresolved`. A definition under a name its file already had is another
definition: a copy that was already there never inherits a link, nor does one whose text
is only close to the lost one's. The exception is a name that held another text and now
holds the tokens of a removed definition of 30 tokens or more: the commit put that
definition under a name the file already had (a class moved onto the name another class
gave up, a helper inlined into its only caller), and rule 1 follows it there.

A definition under 30 tokens is mostly its signature. It is told by its tokens only with
its name or its scope, and by its text under another name only token for token: its
tokens under a condition it did not have before read `changed`.

- From module level it goes, into any scope, under a name of the same words (`_read_rows`
  or `read_rows_v2` for `read_rows`), and to the module level of another file under a name
  that holds those words with more before or after them, or one those words hold
  (`bulk_read_rows` or `read_rows2` for `read_rows`, and `read_rows` for either). A name of
  one word is held by any name about the same thing (`Error` by `ReadError`), so it counts
  only with a number after it (`D2` for `D`).
- A member, whose name any class may define, goes only with its class, under a name
  related to its own. That class is the one renamed alone or with nearly its text, or the
  one keeping its members' names, once no member of it is left in its file: at least half
  of them, or two when one more of its members, of 30 tokens or more, came with its
  tokens. Under its own name the member is one of those two, so that one larger member is
  then all that tells the class. Or it is the class that two more of its members, of 30
  tokens or more each, left for with their tokens under their names.

A range that changed more than 32 files under the entry's `path_prefixes` is not parsed
whole: the definition is looked for in the files that hold, at either end of the range,
one of its three longest lines without its name, by a search of the mirror. Only those
files and the link's own are parsed, so a removed or kept definition in a file that holds
none of those lines contests nothing. That search is not made for a definition with no
such line of 12 characters or more, when those files are more than 32 with the link's
own, when more than `memory_code_links_mirror_changed_files` changed (a warning in the
server log names the range), or when git cannot run or finish it, which is then not tried
again for the other links of that range in the pass; nor is a range searched whose diff
cannot be read. Over a range not searched a live link is read as if nothing was renamed.
An `unresolved` link is looked for from the commit its code was last read at, so its
range grows with every commit. While that range is within 32 files, the link is followed
once one definition that may be it is left. A wider range is read only where its lines
are, which cannot show that the definitions that left it `unresolved` are gone: the link
is followed when that read finds the one definition that is it, and stays `unresolved`
otherwise, as over a range that is not searched.

The `memory_code_links` worker's pass outcome counts in `wide_ranges` the ranges past 32
files its own pass followed, not those a `code.refresh` call followed first. A `missing`
link comes back only when its own name does. A definition moved to another file under its
own name with an edit is followed there when its text is close to the one the link last
read. A new definition left where it was stops that search only when it may be the old
one under a new name: an export list or an unrelated function added beside it does not. A
name gone from its file is looked for in the files changed since its last check as the
mirror holds them, beside the index, so a definition moved by a commit the index has not
taken in whole (past `code_ingest_max_files_per_commit`) is followed when the link is
rechecked. When `memory_code_links_mirror_naming_files` or more of those files name it,
or more than `memory_code_links_mirror_changed_files` changed under the entry's prefixes,
or the diff cannot be read, or the paths are more than git takes in one command or
searches in its time, the mirror adds nothing and the index decides. When git cannot run
the search, or a definition it finds cannot be fingerprinted, a live link the index's
namesakes do not settle is `unresolved`. Files the ingest would not index (outside the
entry's `path_prefixes`, refused by its denylist, over the byte cap, binary) add no
definition; a generated file, which the ingest declares without searching its text, does.
A file the parser fails on keeps its links as they were until it parses. When the
fingerprint rules change, every link is re-hashed from the commits its hashes were taken
at. When its old text is gone from git, a link that matched it takes the text the next
check finds and a changed one stays `changed`; one whose old text no longer parses keeps
its last state, and the worker reports it.

After a rename a memory's text still says the old name until it is revised, by the
link pass where the swap is certain ([below](#a-memorys-text-after-a-rename)) or by a
person. Until then the reads that serve its links (listed below, `namespace.validate`
apart) name where the code is now. A link that is `fresh`, `moved` or `changed` at another path or symbol than
the memory was written against is served with both: the current `path`, `symbol`,
`start_line` and `end_line` (trunk's, at the link's last check), and `was_path` and
`was_symbol`, the oldest of the identities the link keeps (its last 16; a claim the
`revise` policy found to hold is re-anchored where the code is and still carries them).
A link to a file carries the path it was written against and no lines. A definition
renamed back to its first name carries neither, nor does an `unresolved` or `missing`
link, nor a link to a definition that replaced a link to its file. In text the line
reads
``(code moved: `reader::fetch_rows` is now `reader::load_rows` at src/reader.py:12-40)``;
a line whose code also changed keeps its warning and adds the same clause. A line names
two such links and counts the rest. Naming the place moves no result: a `moved` memory
keeps its rank.

The namespace's `code_change_policy` (`namespace.register`) decides what reads make of a
change:

| Policy                     | Removed code                                                                                                                                                                                                                           | Changed code                                                                                                                                                          |
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `retire_removed` (default) | When every link of a memory is `missing` (a pending or `unresolved` one counts as not), search (and `memory.ask`, `context.pack`) leaves it out before it picks its results; `memory.get` still shows it. It is back when the code is. | Flagged.                                                                                                                                                              |
| `flag`                     | Flagged.                                                                                                                                                                                                                               | Flagged.                                                                                                                                                              |
| `revise`                   | As `retire_removed`.                                                                                                                                                                                                                   | The claim is re-checked against the old and new code by the LLM: one that holds is re-anchored, a contradicted one gets a corrected claim as the link's `suggestion`. |

Under every policy, a memory that a search still serves ranks lower when its worst link
is `changed`, `unresolved` or `missing`: it moves below the next
`memory_search_code_changed_places` (3) rows that rank by score (a row also moving down,
or already moved, is not counted), never out of the results nor below a row served only
as filler (under the similarity floor, or flagged below the abstain threshold), after the
confidence and abstain checks have read them in relevance order;
`score_components.code_changed_places` says how far among its own search's rows
(`loom_search` places its merged repository decisions by similarity among the rows its
search did not rank down). These are never moved down:

- a memory a person holds;
- a memory whose only such links are into code the caller may not read, or are links
  nothing keeps current (`memory_code_links_enabled` off);
- a row placed by an identifier match or by an `anchor_first` or `recent_first` tier,
  which a move does not count as a place either;
- every row a search serves for a query whose answer is a date order (`loom_search`'s
  merged repository decisions, placed by similarity, still move);
- the rows of a later page (`page=<handle>`), served in their parked order;
- a chunk, record or summary hit, which carries no `code_state`.

A reader block (`render="reader"`, `loom_search`'s block) whose question carries a time
word (`when`, `after`, `since`, `latest`, …) lists its rows by date, so the move does
not show in it; `results` keeps the move.

`memory.ask` re-sorts the search's rows by similarity and recency while
`memory_ask_recency_weight` is above 0 (0.2 by default), and its identifier
lookups place their own rows; a `context.pack` startup read with no query does not
search: it lists pinned, then recent memories, leaves out a memory whose code is gone
under the namespace's policy, and labels one whose code changed, was not found again or
went, as a search does. A move does not show in any of these.

`revise` judges a changed link once per edit, within a per-pass budget
(`memory_code_links_revise_per_pass`). A memory labelled `high` sensitivity is never sent
to the model. A memory a person pinned, locked (until the lock lapses) or verified, and
one naming more code than the link cap, is only flagged. Links made for an earlier value
of a memory (its text, files, repository or user) are ignored by every read until it is
relinked.

Links are kept against the trunk. On another branch, a lesson compares the branch's own
definition, under any of the link's last 16 names, with the text the memory was written
against: a release branch that still has the old text reads `fresh` after trunk changed
it, and one that has code trunk removed still gets its lesson. Where the branch's files
cannot be read (a host with `LOOM_GIT_HISTORY=none` has no git mirror), a lesson carries
trunk's last state.

The links are read where the code is:

- `code.symbol` attaches the linked memories as `lessons`, each with its `code_state`
  and, when the definition read is at another path or symbol than the memory was written
  against, `code_moved` (on a branch, with the branch's own lines; a branch that still
  has the code under an earlier name gets none, since the text names what it has).
  They come from the repository's team namespace and the `lesson_namespaces` the call
  names (over MCP the caller's memory home when it names none), never from every
  namespace the caller can read. The read is bounded by `code_enrich_timeout_s` and
  serves at most three; when it, or one matched member's read, fails or runs past that
  bound, the definition carries `lessons_unread: true`, so a caller can tell it apart from
  a symbol with none. The lessons it still carries may then be incomplete.
- `code.search`, `code.callers`, `code.callees`, `code.impact`, `code.outline` and a task's
  `code.context_pack` attach `lessons` for the answer's top files
  (`code_result_lessons_paths`): from the same namespaces, less any other repository's code
  namespace, the memories linked to code in each file or naming it by its path or a tail of it
  (a bare filename, `search/handler.py`; an absolute path is trusted to name a file below the
  root that it ends in), each with its `code_state`, within `code_result_lessons_tokens`. Each
  row carries `path`, `memory_key`, `namespace`, `excerpt`, `code_state`, `rev` (the first 12
  characters of the commit its link was anchored at) for a linked row, `first_written` (the
  day it was first written) for a row with a code state, `changed_since` (the
  commit that put its code in a changed, unresolved or missing state) when one is known, and
  `supersedes_key` when it replaces an older row, and `code_moved` (its links to code in the
  file that is now at another path or symbol than it was written against) when there are
  any; a row another row read for the answer supersedes is not served. `lessons_left_out`
  counts the rows the cap, a cut or that rule left out. A decision or constraint is served
  whole or left out. The read runs after the answer, never enters the search memo, and is
  skipped for `include_lessons: false`, with `code_result_lessons` off, or for a token
  narrowed to its own user or session.
- `code.grep` in matches mode focuses inline lessons on the definitions its
  matches name in trunk files. When selecting files to read, grep prefers
  files with a current lesson linked to a matched definition at the returned
  revision. `code.search` focuses a file's lessons when a returned definition
  has a complete linked lesson.
  They count omitted lessons in `lessons_left_out`. Grep keeps lessons when
  the matches and links cannot be checked at the same revision. A line with no
  enclosing definition also keeps lessons with overlapping or unverified ranges.
  File-wide notes, pending or uncertain links, nested definitions, decisions,
  constraints and pins remain eligible. Whole-file search hits, an unavailable
  live link check, or a configured lesson budget use file-level selection. Use
  `memory.for_file` to read the broader file history.
- `memory.for_file` serves memories linked to code in the file beside those whose
  `files` name it. A line whose code changed, was not found again or went says so and
  names the first indexed commit at which it read so, and a line whose code is now at
  another path or symbol says where (each hit lists those links as `code_moved`);
  `context.pack` decision lines carry the same note, and its memory lines a
  `code_state=<state>` label (`<state>@<commit>` when a commit put it there) with
  `(code moved: …)` ahead of the text.
- `memory.get` returns the links as `code` (each with its lines, any `suggestion`, and
  `was_path` and `was_symbol` when the code moved); `memory.search` hits
  read from a memory's own row carry its worst link as `code_state` and, when that is
  `changed`, `unresolved` or `missing`, the commit that put it there, when one is known,
  as `code_changed_since`, and the links now at another path or symbol as `code_moved`
  (a chunk, record or summary hit carries none of these and is never
  left out). A `render="reader"` block and every page of `loom_search`'s text say so on
  such a hit's line, with the same note as a `memory.for_file` line. Where the
  deployment sets `memory_ask_code_namespace` to a code namespace the caller may read
  and leaves `memory_ask_code_staleness` on, `memory.ask` gives its synthesis a note of
  the memories whose code moved, changed or went, with the same clause for a link now at
  another path or symbol.
- Each of those reads says of a memory that names code which state it is in, the commit
  its link was anchored at (`code_rev` on a search hit, `rev` on a line or a lesson) and
  a day, under a label that says which day it is. `first_written` is the day of the
  memory's first write: a `memory.for_file` line, a lesson (the field `first_written`)
  and a startup recall line print it, and no later write moves it. `written` is the day
  the text served was written: a line of a search hit prints it from the hit's
  `created_at`, the search document's, which a write of the text (`memory.set`,
  `memory.update_by_id`) and `memory.restore` stamp again. For a memory whose text was
  written again or restored, `written` is therefore a later day than `first_written`.
  Neither is the row's `updated_at`: an unpin, a lock, an unlock or a label moves neither.
  The commit is the repository's indexed head when the link was made or last re-anchored;
  for a link made after its memory that is a later commit than the writer worked at.
  A search hit read from a memory's own row that shows no link state, and whose text
  names a file by a path with a directory, is `unlinked`: the read has no comparison
  with code to show for it. Where no repository is indexed that is every such hit, and a
  hit whose only link is pending or in a repository the caller may not read is marked
  the same way. A `memory.for_file` line and a lesson are marked likewise; a memory that
  names its file only in `files`, by a bare file name or by a symbol is not. `unlinked`
  is a label a read gives: no row and no parked search page stores it.
  A reply that serves a memory with a code state says once what was compared: no code
  for an `unlinked` memory, and for every other state the repository as Loom indexed
  it, which is not the caller's checkout. That sentence is `code_note` on
  `memory.search`, the first line of a reader block, of a `context.pack` block and of
  `loom_search`'s plain lines, the line after the header of a `memory.for_file`
  block, and the `note` of a review brief's `rationale` section, whose rows carry the
  `memory.for_file` line. A block takes the sentence's room from the budget of the row
  that prints with it, so a row left out takes its part of the sentence with it.
- `namespace.validate` lists memories whose code changed, was not found again or is
  gone, in the repositories the caller may read, and the edits that bring a memory's
  text up to a rename its link followed.

A memory with no link carries no link state: a read marks it `unlinked` when its text
names a file by its path, and serves it without a label otherwise. `namespace.validate`
counts the served memories that name code (a backticked or qualified name, a call, or
`files`) and hold no link, by cause, as `info` findings:

| Check                            | The memory                                                                                                                                                                                                                 |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code_unlinked_no_repository`    | names no repository Loom indexes that the caller may read: no `repo:<id>` tag of one, and not written in a code namespace. It is never linked.                                                                             |
| `code_unlinked_file_not_indexed` | lists `files`, none of which is a path on the indexed trunk (not merged yet, outside the index, or a bare filename two files share), and no name in it is one definition.                                                  |
| `code_unlinked_name_unresolved`  | lists no `files`, and each name is defined nowhere on trunk or more than once.                                                                                                                                             |
| `code_unlinked_pending`          | waits for its link; each sample says what it `waits_for`: `link_pass` (the worker has not read this write), `index` (no index yet, or a file that does not parse) or `trunk` (a qualified name trunk does not define yet). |

The counts are of the 2,000 served memories last written (of those under `keys` when
given), and only in an org that indexes a repository; a raw tool observation, which is
never linked, is not counted. How far each repository's links trail its
index is a gauge, and a health warning when it lasts
([monitoring](/docs/operations/monitoring#what-to-alert-on)).

### A memory's text after a rename

A `moved` link is at its code, and the memory's text may still name the old definition or
path. The link pass that follows the rename plans the edits that bring the text up to it
and applies them itself when all of these hold:

- the plan offers edits: none of the reasons in the table below applies;
- the memory is held in the repository's code namespace, as a team rule or decision
  is. A memory of any other namespace is linked through its `repo:` tag, which its
  writer set and which grants nothing: its readers may hold no role on the repository,
  so the new name or path is not written into it;
- no person holds the memory (pinned, locked or verified), and no service account
  attested the text as it is, which a revision would leave stale;
- the memory is `active` and not labelled `high`. One flagged `conflicted` keeps its
  text: a revision would drop the flag on its side while the other memory keeps its own;
- the repository is indexed on one branch. Another indexed branch may still define the
  old name, and a memory linked again from its revised text is no longer served there;
- the org's model calls are not switched off. The revision embeds the new text, so the
  pass revises nothing in such an org and takes its memories up once the calls are back
  on.

The revision is one `memory.update_by_id` write on the hash of the text the edits were
planned for, so a memory rewritten in the meantime is left alone. The write reads the
memory again under its key's lock, and one pinned, verified, attested or no longer
`active` since the pass read it keeps its text. It runs that write's
blacklist and conflict checks, embeds the new text and closes the facts the old value
stated, as any revision does. Nobody asked for it, so it changes that memory alone. It is
not written where a caller's revision would do more: the conflict check finds the revised
text a duplicate, a restatement, a refinement or a contradiction of another memory, or
the conflict resolver would judge it against one. It also retires no other row of the
same key. Such a memory keeps its text and is listed with its `edits`.

The new version stays its writer's row (`actor` is kept) and leaves an audit row by
`process:code_rename` and a `memory.revised` event; `memory.history` keeps the text it
replaced. Its `source_class` is never raised. A row its writer asserted is `derived` from
then on, since the text is no longer what they stated, so search no longer prefers it in
a near-tie (`memory_search_asserted_boost_scale`). Every other class is kept: an
unattested `external` row stays out of `memory.ask` synthesis. The next pass
links the revised memory where the code is, and it reads `fresh`. The `memory_code_links`
pass outcome counts the memories revised as `renamed`. A link followed with an edit to
its code reads `changed` and its memory's text is never revised: whether the claim still
holds is the `revise` policy's question. A recheck made inside a `code.refresh` call
revises nothing and leaves the memory to the worker's next pass.

Every other memory keeps its text. `namespace.validate` lists each memory whose text
still names an old definition or path under the `info` finding `code_rename_edits`,
with either the `edits` its text allows (replace `old` with `new` from `start` to `end`,
counted in Unicode code points of the text, where the text reads `old`) and the
`content_sha256` they are of, or the one `reason` no edit is offered. The finding's
`totals` count the memories by `edits` and by reason. A memory listed with `edits` is one
the link pass left (held outside the repository's code namespace, held by a person,
attested, flagged `conflicted`, in a repository indexed on more than one branch, or
close to another memory once revised) or has not reached yet. The
pass decides once, when its link follows the rename: a memory it left then is not
revised later, and neither is one whose link already read `moved` under a build that
revises no text ([rule 67](/docs/architecture/rolling-upgrades#the-rules)). Those stay
listed until a principal applies the edit. The report writes nothing: to apply an edit,
read the sentence it changes, then call `memory.update` on the key with the revised text and
`if_match_sha256` set to the listed hash. That is a revision by the caller, with its
conflict check, and it is refused when the memory changed after the report read it. The
link pass then links the revised memory where the code is.

An edit is offered only for a name written as code (a whole backticked identifier, an
`A::b`, or a call written `a.b(` or `name()`) and for a whole repository path, in the
spelling the text uses: `Reader.get` becomes `Reader.fetch`, a full dotted name becomes the
full new one, and `self.get` keeps its receiver. The whole memory gets no edit for the
first of these reasons that applies:

| Reason                   | The memory                                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `not_text`               | has a value that is not one string.                                                                                                                                                                                                                                                                                                                                                                             |
| `link_not_settled`       | has a link that is pending, `changed`, `unresolved` or `missing`, that its renamed class carried, or that is hashed under older fingerprint rules.                                                                                                                                                                                                                                                              |
| `incomplete`             | names more code than the link caps keep.                                                                                                                                                                                                                                                                                                                                                                        |
| `overloaded`             | is linked to a definition the index numbers among several of one name.                                                                                                                                                                                                                                                                                                                                          |
| `quoted_or_literal`      | holds the old name or path in a fenced block, a URL, a quoted string or a backticked span that is more than one name.                                                                                                                                                                                                                                                                                           |
| `prose_occurrence`       | writes the old name as a bare word of the prose.                                                                                                                                                                                                                                                                                                                                                                |
| `old_name_remains`       | would still hold the old name or path where no edit reaches: a plain word, a part of a longer name, a longer name written as code that names no definition on the indexed trunk (`conn.read_rows()`), the dotted module the definition left (two segments or more) outside a name written as code that names a definition on the indexed trunk, a path before a line number, or a path whose file still exists. |
| `names_several`          | writes one name that two of its links were written against.                                                                                                                                                                                                                                                                                                                                                     |
| `receiver_form`          | writes the name as `self.name`, `cls.name` or `this.name`, and its `files` do not name the defining file.                                                                                                                                                                                                                                                                                                       |
| `old_name_still_defined` | spells the old name in a way that still names a definition on the indexed trunk.                                                                                                                                                                                                                                                                                                                                |
| `new_name_present`       | already holds the new name or path.                                                                                                                                                                                                                                                                                                                                                                             |
| `dated_claim`            | is dated (`valid_to`, `invalid_at` or `temporal_anchor`), or the sentence to edit holds a commit hash, a version tag, a year, a month (`May` only capitalised after another word), or a pull request or issue number.                                                                                                                                                                                           |
| `about_naming`           | would be edited in a sentence about the name or the place: it holds `name`, `names`, `named`, `naming`, a word that starts with `renam` or `alias`, `called`, `formerly`, `used to`, `replaced`, `moved from`, `deprecated`, `legacy`, `before` or `previously`.                                                                                                                                                |
| `named_in_key_or_tags`   | holds the old name or path in its `memory_key` or a tag.                                                                                                                                                                                                                                                                                                                                                        |
| `named_in_files`         | lists the old path in `files`, which `memory.update` keeps.                                                                                                                                                                                                                                                                                                                                                     |
| `would_unlink`           | would lose a link once revised: the new name is not one definition on the indexed trunk, or the revised text no longer names a definition or file it is linked to.                                                                                                                                                                                                                                              |

A memory whose text names no old name or path is not listed, whatever its links, key, tags
and `files` say: its bare name still holds after a move, or the link is back where the text
says. A sentence ends after `.`, `!` or `?` and a space (not after a one-letter abbreviation
such as `e.g.`), at a blank line and before a list item; a line break alone does not end
one. The words that mark a sentence as
being about the name are English, and `call` or `calls` is not one: it is read as calling
the code. The finding reads the 2,000 memories whose `moved` link was last checked (of
those under `keys` when given), in the repositories the caller may read, and no
high-sensitivity memory; a link whose code also changed is listed under `code_links_stale`. Neither the
memory's key, tags, `files`, entities and concepts nor a line number written in its text
is edited.

## Time

| Column            | Axis   | Meaning                                                                                 |
| ----------------- | ------ | --------------------------------------------------------------------------------------- |
| `valid_at`        | world  | When the fact became true, as the writer stated it. `NULL` = unknown.                   |
| `valid_to`        | world  | When the fact stopped being true. A read drops a row past its `valid_to`.               |
| `temporal_anchor` | world  | The date the fact is about (an event date), set by extraction.                          |
| `created_at`      | record | When Loom wrote the row.                                                                |
| `invalid_at`      | record | When Loom retired the row (supersession).                                               |
| `tombstoned_at`   | record | When the writer deleted it.                                                             |
| `expires_at`      | record | When the row leaves the served set, if its writer or the namespace owner set an expiry. |

An `as_of` read replays one axis. `as_of_basis="valid_time"` (the default) asks what was
true at T: rows whose best world date (`valid_at`, else `temporal_anchor`, else
`created_at`) is at or before T. `as_of_basis="knowledge_time"` asks what Loom had
learned by T: rows written by T and not retired, deleted or invalidated by T.

Under `newest_wins`, a templated substitution retires the peer only if the peer's
`valid_at` is not later than the new row's, so a backfill of old facts does not retire
current ones. This is valid time plus a retirement stamp, not a bi-temporal model:
supersession, not exclusion by date, decides which of two rows is current. A full
interval model would need every writer to state when each fact ended, which agents
rarely know.

## Versions and history

Every change (value edit, tombstone, restore, lock, status flip) is a new row with a
higher nanosecond `version` and every other column carried forward. Merges drop old
versions, so `loom.memory` is the current state, not a history.

The history is `loom.memory_versions`, an append-only mirror filled by a materialized
view on every insert. `memory.history` reads every version of a key;
`namespace.rollback` returns every head in a namespace to its version at a point in time;
`memory.redact` scrubs a historical value and keeps its audit entry. `content_sha256` on
each version is what `if_match_sha256` compares and what an attestation binds to.

## Provenance

The server stamps two columns on every write and never takes them from the body:

- `actor`: `human:<subject>` or `process:<subject>` (a service account), from the token.
- `source_class`: how Loom came to hold the content, from the operation and the token.

| `source_class` | Means                                                                         |
| -------------- | ----------------------------------------------------------------------------- |
| `asserted`     | A caller stated it directly (`memory.set`).                                   |
| `extracted`    | The extraction pipeline inferred it from a transcript.                        |
| `observed`     | Loom recorded it from activity it saw.                                        |
| `derived`      | Computed from other memories (consolidation output, session digests).         |
| `imported`     | Loaded from another system by an importer.                                    |
| `external`     | Declared by the writer as outside content: a tool result, a page, a document. |

A request may only declare a downgrade (`derived`, `external` or `imported`); anything
else is a 422. Text an agent copies from its environment is what an attacker controls,
so `memory.ask` keeps unattested `external` rows out of its synthesis
(`LOOM_MEMORY_ASK_EXCLUDE_UNVERIFIED_EXTERNAL`, default on), and
`LOOM_MEMORY_SEARCH_TRUST_WEIGHT` can lift asserted and attested rows in ranking.

- **Lineage.** Consolidation writes `loom.memory_belief_sources` rows; a session digest
  lists the keys it summarised in `session_summaries.derived_from`. `memory.provenance`
  says where a row came from, `memory.evidence` returns the conversation turns an
  extracted fact was drawn from, and `memory.lineage` walks how a shared memory was
  promoted.
- **Attestation.** `memory.verify` records who vouched for the content, bound to its
  hash. Reads report `verification`: `human` or `process` while the content is unchanged,
  `stale` once it changes, `none` if never attested. An edit keeps the attestation and
  reads as `stale`; it never transfers trust to new content.

## What goes where

| It is…                                                     | Plane                                               | Why not memory                                                                                      |
| ---------------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| A fact still true next week that another session needs     | **Durable memory**, `memory.set`                    | It is memory.                                                                                       |
| A transcript the user wants remembered                     | `memory.set_from_messages` (extraction)             | One large row is findable only as a whole; extraction writes one short fact per key.                |
| The current plan, a lease, a cursor, "where was I"         | **Working memory**, `working_memory.*`              | Coordination state changes every step; ranking it pollutes recall.                                  |
| A large tool result you may re-read                        | `context.offload` / `context.fetch`                 | It is a blob to fetch by key, not a claim to rank.                                                  |
| The resumable state of one line of work                    | **Session briefs**, `session.brief_*`               | A brief is restored by choice, never ranked into another task's answer.                             |
| A document, spec or runbook; anything over a few kilobytes | **Knowledge**, `knowledge.add` / `knowledge.upsert` | Documents are chunked by heading; a memory is embedded from an excerpt of at most 1,200 characters. |
| A chat turn log                                            | **Conversations**, `conversation.*`                 | Turns are evidence, not beliefs; `memory.recall` reads the turns an extraction used.                |
| Data with identity and exact fields (a PR, a ticket)       | **Records**, `memory.record.*`                      | Records fold field by field and filter exactly.                                                     |
| Always-loaded persona or preferences                       | **Profile**, `profile.*`                            | Fetched by label every time; ranking it against questions wastes the slot.                          |

For documents: store the document in knowledge and write one short memory under a
readable key that says what it is and points at it. `context.pack` loads working memory
ahead of the durable sections, so an agent sees its own state first.

## Retention

Loom deletes only what its writer asked for. No memory table has a default TTL and no
sweep retires rows by age. A row leaves the served set when its writer deletes or
supersedes it, when its writer gave it an expiry (`ttl_seconds`, `valid_to`), or when the
namespace owner or operator configured a retention window. `memory.restore` reverses an automatic
tombstone within 14 days when no permanent refusal exists.
[Retention and erasure](/docs/features/memory/retention-and-erasure) covers the settings
and the erasure saga.

## One fact over time

In March a user says "I live in Delhi"; in June, "I moved to Berlin."

- **June write.** Extraction mints the key from the subject and attribute, so both
  statements land on the same key. The June row does not overwrite March: the Delhi
  version stays in `loom.memory_versions`, readable with `memory.history`.
- **A misfiled fact.** If Berlin lands under another key, the peer search finds the
  Delhi row close but different and marks both `conflicted`, linked by `conflict_with`.
  The namespace policy decides what follows (see
  [how a write is judged](#how-a-write-is-judged)).
- **"Where did they live in April?"** An `as_of` read answers it, by when the fact was
  true or by what Loom knew at that date ([time](#time)).
- **"Who said so?"** `actor` and `source_class` record the writer and how the fact
  arrived; `memory.evidence` returns the turns an extracted fact came from.
- **A bad import.** `namespace.rollback` returns every head in the namespace to its
  version at a point in time, and runs as a dry run unless told otherwise.

## Example

Write a fact, probe a change before writing it, then update against the hash you read:

```python
import asyncio
import os
from datetime import datetime, timezone

from loom import Datapack


async def main() -> None:
    dp = Datapack(
        org="acme",
        namespace="eng-tooling",
        base_url=os.environ["LOOM_BASE_URL"],
        api_key=os.environ["LOOM_API_KEY"],
    )
    agent = dp.agent("release-bot")
    key = "project/billing/deploy-window"

    out = await agent.memory.set(
        memory_key=key,
        value="Billing deploys only on Tuesdays and Thursdays, never on Fridays.",
        tags=["kind:constraint", "service:billing"],
        entities=["billing"],
        valid_at=datetime.now(timezone.utc),
    )
    print(out["conflict_verdict"], out["content_sha256"])

    probe = await agent.memory.set(
        memory_key="project/billing/deploy-days",
        value="Billing deploys only on Thursdays.",
        dry_run=True,
    )
    if probe["conflict_verdict"] == "conflict":
        peer = probe["peers"][0]  # closest peer, with its key
        current = await agent.memory.get(memory_key=peer["memory_key"])
        await agent.memory.update(
            memory_key=peer["memory_key"],
            value="Billing deploys only on Thursdays.",
            if_match_sha256=current["content_sha256"],
        )


asyncio.run(main())
```

A 409 `PRECONDITION_FAILED` on the update means another writer changed the row after the
read: read again and decide again. Over HTTP the write is `POST /v1/memory.set`; over MCP
it is the `loom_memory_set` tool.

## Related

- [Identities and namespaces](/docs/concepts/identities-and-namespaces), [retrieval and ranking](/docs/concepts/retrieval-and-ranking)
- [Writing memories](/docs/features/memory/writing),
  [conflicts and refusal](/docs/features/memory/conflicts-and-refusal),
  [history and provenance](/docs/features/memory/history-and-provenance),
  [working memory and profiles](/docs/features/memory/working-memory-and-profiles),
  [knowledge](/docs/features/knowledge)
- [Memory architecture](/docs/architecture/memory-architecture): the write path in code
- [Operations](/docs/reference/operations#memory), [settings](/docs/reference/configuration#memory)
