---
title: Runs
lastModified: '2026-12-05T05:57:06.000Z'
description: A run is one execution of a task, such as "triage issue 1234". run.begin opens it and returns a run_id; the agent passes that id on its writes (memory.set,…
---

A run is one execution of a task, such as "triage issue 1234". `run.begin` opens it and returns a `run_id`; the
agent passes that id on its writes (`memory.set`, `memory.update`, `observe.record`); `run.complete` closes it with
a status, the memories the agent relied on, and optionally a reflection. A body `run_id` on a read (`memory.search`,
`memory.ask`) filters to the run's own rows, so reads are labelled instead: by the `X-Loom-Run-Id` header over HTTP
(`run_scope` in the Python SDK), and by the session's run over MCP, which a run opened there records
([MCP sessions](#mcp-sessions)). A memory that a successful run relied on
ranks higher next time; one that a failed run relied on loses the boost it earned.

## What a run records

A run row lives in `loom.agent_runs`. Most of what `run.get` shows is derived at read time from the other planes:

| Field                              | Stored or derived | Source                                                                                                                                                  |
| ---------------------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `goal`, `user_request`, `model`, … | stored            | `run.begin`                                                                                                                                             |
| `status`, `final_response`         | stored            | `run.complete` (`active` until then)                                                                                                                    |
| `memories_used`                    | stored            | `run.complete`: the agent's own statement of what it relied on                                                                                          |
| `grade`, `grade_source`, …         | stored            | `run.grade`, after the run closed                                                                                                                       |
| `memories_written`                 | derived           | rows in `loom.memory` carrying the run's `run_id`                                                                                                       |
| `recalled`, `recalled_keys`        | derived           | the search trace log under the `run_id`, unioned with `run.complete(recalled_keys)`                                                                     |
| `observations`                     | derived           | episodic rows from `observe.record` tagged with the `run_id`                                                                                            |
| `turns`, `cost_usd`                | derived           | the session's turns in `loom.agent_turn_usage` made while the run was open (written by the Claude Code plugin, or by an agent with `cost.record_turns`) |
| `budget_usd`, `budget_seconds`     | stored            | `run.begin` (0 = no budget)                                                                                                                             |
| `elapsed_seconds`, `over_budget`   | derived           | from the run's start to its close (or now), on the server's clock, and `cost_usd`, against the budget                                                   |

`recalled` is `-1` when `LOOM_SEARCH_TRACE_LOG_ENABLED` is off and no `recalled_keys` were sent.

Which revision of a memory row or document a read of the run carried is kept apart, in
`loom.read_receipts` under the run's `run_id`, so it can still be told after the item
changes. Not every read writes a receipt
([what gets none](/docs/architecture/read-receipts#what-gets-none)): a missing one means
"not recorded", not "not served". `run.reliance` lists a run's receipts beside what its
client reported ([what a run read](#what-a-run-read)); any other question of the table
is answered with SQL
([reading the table](/docs/architecture/read-receipts#reading-the-table)). For a run
opened over MCP, its session's reads made while it was open are there under the run's
own id and under its session's run, except those filed under `-` or under another run
the read names ([MCP sessions](#mcp-sessions)).

`metadata` holds the client's key/values beside keys the server writes. One key has a
fixed meaning and is the server's alone: `session_run`, the id of the MCP session's run,
recorded on a `run.begin` over MCP ([MCP sessions](#mcp-sessions)). One a client sends
is dropped. A stored value is read by its form (`mcp-` and 40 hexadecimal digits), which
does not prove that the server wrote it: a build that does not reserve the key stores a
client's value there ([the receipt row](/docs/architecture/read-receipts#the-receipt-row)).
The server also writes `role` (from `run.begin`) and `recalled_keys` (from
`run.complete`), and on a session's own run `implicit`, `transport`, `subject` and
`closed_by`, so a client's value under one of those names can be replaced.

Metadata is kept to 8,000 characters in two steps. The last `recalled_keys` are dropped
first. If the text is still over, a marker (`_truncated`, `_bytes`) replaces it, which
keeps `implicit` and `subject`, and `session_run` when it has the session-run form.

## Budgets

`run.begin` takes an optional `budget_usd` (model spend) and `budget_seconds` (how long the run may take). `run.get`
compares them with `cost_usd` and `elapsed_seconds` and lists the ones the run has gone past in `over_budget`
(`cost`, `time`, or both). Loom does not run the agent, so a budget is a signal for whoever does, never a stop.

A run's spend is its session's turns made while the run was open, by each turn's own time (`turn_at`, from the
transcript), so `budget_usd` needs a `session_id` (a 422 otherwise). It is kept to 6 places, like cost, so the
smallest is $0.000001. Time runs from the run's start to its close on the server's clock, whatever `duration_ms` the
client reported. Set the budget in the run's first `run.begin`.

The first `run.get` in a session that finds an active run over budget also carries the mentor hint
`run_over_budget`, which the plugins hand to the model as advice. A closed run still reports `over_budget` but gets
no hint. Like every mentor hint it is said once per session, and a caller that sends no session (the SDK, plain
HTTP) shares one per namespace and web process, so decide on `over_budget`, not the hint.

Limits:

- **Between prompts only.** The Claude Code plugin posts a prompt's turns when it ends (an agent can post its own
  with `cost.record_turns`), so a cost budget is checked between prompts, and a single headless prompt
  (`claude -p`) shows its spend only after it finishes. Those turns still count when they arrive after the agent's own
  `run.complete`. A call's cost is known only after it returns, so a run can go past `budget_usd` by its last
  turn's cost before anything sees it.
- **The client's clock.** The window compares the client's turn times with the server's run times; a clock minutes
  off misplaces the turns at a run's edges. A turn keeps the time it was sent with, so a re-sent turn stays with
  the run it first fell in. One sent without a time (or with one that does not parse) takes the time its
  `message_id` is recorded with, or now if it is new; a re-send within a fraction of a second of the first may
  still be dated now. `cost.record_turns` answers with `turns_dated_ahead`, the turns it received dated more than
  5 s after the server's clock, so a caller that posts turns itself can see a fast clock; the Claude Code plugin
  posts them without reading the answer.
- **One session, many runs.** Runs open at once in one session see the same turns: a nested run counts toward both,
  and concurrent workers that each want a cost budget need their own sessions.
- **Unpriced models.** A turn whose model the price table does not know costs 0; `run.get` counts those in
  `unpriced_turns`, and they do not count toward `budget_usd`.
- **MCP.** The MCP tools offer only `budget_seconds`, since the model does not know the session id its turns are
  recorded under.
- **Retries.** A re-sent `run.begin` replaces the run's row like any retry: it keeps the session and budget it does
  not restate, a new non-zero budget replaces the old one, and 0 keeps it.
  A new `budget_usd` must be sent with its `session_id` (a 422 otherwise); a new `budget_seconds` needs nothing else.
  A re-sent begin that moves the run to another session drops its cost budget, which was set for the old
  session's turns, keeps its time budget, and says so in its `next`. That is the only way a budget is removed.
  When `run.begin` answered with a different `run_id` than the one sent, re-send that `run_id`, or the same
  `session_id`; otherwise the retry opens a new run.

## Recalled is not relied on

Two lists travel on `run.complete`:

- **`memories_used`** — the keys the agent actually relied on. Each gets a `used` usage
  event, plus an `evidence` event on a positive outcome or a `harm` event on a negative
  one. `outcome` defaults from `status`: `completed` is positive, `failed` is negative,
  `cancelled` is none.
- **`memories_delivered`** — optional: the keys the client put in front of the model.
  When it is set, a `memories_used` key outside it earns nothing and `undelivered` in
  the response counts those keys. A client that trims recalled memories to fit a prompt
  sends the keys it kept; `[]` credits nothing. It holds at most 500 keys, as
  `memories_used` does, so a client whose prompt showed more sends only the used keys
  among the delivered ones, as the Python SDK's `RunScope` does.
- **`recalled_keys`** — the keys Loom's tools served during the run (the Claude Code
  and Codex plugins stash them from `loom_search` and `memory.get` results and send them
  at session end). They are recorded for `run.get` and never credited.

A row that was returned but ignored earns nothing; crediting every search hit would reward whatever ranks first.
The `usage_fold` worker folds the events into the reinforcement term that
[memory search](/docs/features/memory/search-and-ask) ranks by. A `harm` event takes back earned boost, floored at the row's
write-time base, so one bad run never pushes a row below its relevance and never deletes it.

On a `memory.get` request ledger row, `out_memory_id` and `out_version` in `args`,
when present, identify the revision the server answered with. An `if_version` poll
can report that same revision without reading out the value. It records
`out_unchanged = 'true'`. A regular get records `'false'`. An older row without the
flag leaves the poll outcome unknown. A get can request only metadata, and an MCP
client can receive a trimmed response. These fields do not establish use by the agent.

A procedure key named in `memories_used` also gets a row in the procedure ledger (path
empty, `ok` from the outcome); an agent that calls `procedure.record_run` itself should
leave that key out of `memories_used` so the run is not counted twice. See
[procedures and learnings](/docs/features/memory/procedures-and-learnings).

## What a run read

`run.reliance` lists the items one run read, the revisions it was served, and what its
client reported relying on. The answer joins two sources and keeps them apart:

- An item is **served** when an answer of Loom carried it. The run's
  [read receipts](/docs/architecture/read-receipts) are the record of that.
- The **report** is `memories_used`: the client's own statement, as the run's last
  `run.complete` kept it. A close keeps a key only when it names a live memory of the
  run's namespace. A key of another namespace, a key with no live row and a passage id
  are in no report. A later `run.complete` that names no memory, or a `run.begin` sent
  again, leaves the run with no report.

Each item has one state, true as of the read:

| State                 | The dashboard's label                      | Shows                                                                                                                      | Does not show                                                                                                                              |
| --------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `returned`            | Recalled                                   | Loom served the item under the run.                                                                                        | That the agent read or used it.                                                                                                            |
| `reported`            | Reported as relied on                      | The client named the item, and the record holds it at the revisions listed.                                                | Which of those revisions the agent relied on.                                                                                              |
| `reported_and_served` | Recalled, and reported as relied on        | The report names a revision the record holds. `memories_used` names keys and no revision, so no report reaches this state. | That the item changed the agent's answer.                                                                                                  |
| `not_recorded`        | Reported as relied on, recall not recorded | The client named the item, and the run has no record of it.                                                                | That the item was not served. It is never a mismatch: [what is not listed](#what-is-not-listed) gives the reasons a record can be missing. |

An item's `revisions` are what the record holds, highest version first, and each one's
`versions` are the stored versions under which the run was served one content. For a
memory each is the version of the stored row the read held, as decimal text: the memory
row's, its search document's or a shared copy's, by the kind of read
([the version and the hash](/docs/architecture/read-receipts#the-version-and-the-hash)).
`memory.history` lists versions of the memory row alone, so a version served by a search
hit can be absent from it. The dashboard shows the time that version encodes. For a
document each is its revision number. A `not_recorded` item has no revision: the answer
never fills in the item's latest.

`run.get` answers a different question from other sources: its `recalled` and
`recalled_keys` come from the search trace log and the keys a client sent at the close,
this list from the receipts, so the two can differ.

The answer holds at most 500 recorded items and the 32 highest recorded pairs of content
hash and version of each. A version read with and without its hash is two pairs, and a
receipt that names no revision is one, so an item past its 32 pairs can list fewer than
32 versions, or every version the record holds. Past either bound `truncated` is true;
every reported item is kept, then the items served most recently.

Those bounds are on the answer, not on the read. The read's cost grows with the receipts
the namespace keeps and with the receipts that carry the run's id. An id that one
long-lived client sends on every read is the costly case: it is one list of every read
labelled with it. The read runs under the caller-shaped caps
(`LOOM_CH_CALLER_SHAPED_MAX_ROWS_TO_READ` and its time and memory peers); one that needs
more answers 422, and a run id of its own for each run avoids it. A read past the read
deadline (`LOOM_CH_TIMEOUT_READ_S`, 30 s by default) fails the op. Neither answers a
partial list. [The op that reads a run](/docs/architecture/read-receipts#the-op-that-reads-a-run)
gives the measured cost.

```bash
loom call run.reliance run_id=<id> --namespace <namespace>
```

```python
answer = await agent.run.reliance(run_id)
for item in answer["items"]:
    print(item["state"], item["kind"], item["key"])
```

### What is listed

A read is listed when its receipt names the run. Which reads carry the run depends on the
caller:

| Caller                           | Its reads are listed when                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Any HTTP client                  | The request's body names the run (`run_id`), or the request carries the `X-Loom-Run-Id` header. On a recall read a body `run_id` also filters to the run's own rows, so label such a read with the header.                                                                                                                                                                                                                                                                                                                                                              |
| The Python SDK                   | In a run scope, `memory.search` and `memory.ask` carry the header, and `memory.get`, `memory.bulk_get` and `context.pack` carry the run in their body; `memory.get_by_id`, `procedure.match` and the document reads carry neither. With `auto_run` and no scope open, every `memory.*`, `working_memory.*`, `observe.*` and `context.*` read carries the header; `procedure.match` and the document reads carry none.                                                                                                                                                   |
| The Rust SDK                     | The client is bound to a run: it sends the header on every call.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| The TypeScript, Go and Ruby SDKs | The call's input names the run. These SDKs send no run header.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| An MCP session                   | The read is one the session's run labels ([reading the table](/docs/architecture/read-receipts#reading-the-table) names them). It is listed under the session's run, not under a run the agent opened with `run.begin`: that run lists the reads that name it, and its row names the session's run in `metadata.session_run`, which `run.get` returns ([MCP sessions](#mcp-sessions)). `run.reliance` reads the one id it is given and does not follow that key, so over MCP an agent calls it through `loom_op` once for each id, in the namespace that holds the run. |

A document read with the header:

```bash
curl -sX POST "$LOOM_BASE_URL/v1/knowledge.search" -H "Authorization: Bearer $LOOM_API_KEY" \
  -H 'Content-Type: application/json' -H 'X-Loom-Run-Id: <id>' \
  -d '{"org":"acme","namespace":"support","query":"refund policy for annual plans"}'
```

### What is not listed

- **A read that wrote no receipt**: a request that runs a mirror leg and the other cases
  of [what gets none](/docs/architecture/read-receipts#what-gets-none).
- **An item of another namespace.** A receipt is filed under the namespace that holds
  the item, and a report keeps only keys of the run's namespace.
- **A read older than the receipts' lifetime**
  ([the receipt row](/docs/architecture/read-receipts#the-receipt-row)).
- **Which passage of a document was served.** A document is listed once, with its
  revisions.
- **Who read.** A run id on a read is client input: any caller that can read the
  namespace can label a read with a run's id, so the list can hold another caller's
  reads of the namespace's items, and it never names a reader.
- **The agent's own reads over MCP, for a run a plugin's hook opens.** The hook's run
  lists the items of the context packs the hooks requested. The reads the agent makes
  over MCP are filed under the session's run, a second row of the Runs list, which the
  list shows with "Show runs with no memory activity" while that run saved and reported
  nothing.

## Taking back a run's credit

`run.retract_credit` cancels the `used`, `evidence` and `harm` events that a run's
labels wrote: `run.complete(memories_used)`, `memory.outcome` and `memory.outcome_run`
under the run. Use it when a client credited memories the model never read, or when a
run's verdict was wrong. It never deletes anything. Each label gets a compensating event
with the negated count, so the usage totals net to zero and the history keeps both events.
The next `usage_fold` pass writes the memory's reinforcement back from what is left.
Neither a compensation nor the label it cancels is activity: the memory's clock goes back
to the later of the last recall, the newest credit that still counts, and the memory's own
last write, so the decay a boost fades by does not restart.

- `run_id` addresses one run. A writer cancels the labels its own principal posted on
  it, and needs the run's row in the namespace's run ledger: a run the writer cannot see
  answers as not found. A namespace admin cancels every principal's labels, and also
  reaches labels whose run has no ledger row in the namespace, since `X-Loom-Run-Id` and
  `memory.outcome_run` can name a run that `run.begin` never opened there. With neither a
  ledger row nor a label of the run, the call answers as not found. A user erasure writes
  `<erased>` as the run of the labels it scrubs that name one, so a run named `<erased>`
  answers as not found to the run form; the window form still reaches the caller's own
  labels on a run a client named so. When the server cannot read the caller's grants to
  tell whether it is an admin, it answers `503 BACKEND_UNAVAILABLE`, writes nothing, and
  is safe to resend.
- `since` and `until`, instead of `run_id`, address a window of at most 30 days, in any
  run or none. They cancel only the caller's own labels, admin or not. `until` defaults to
  now, and `since` is no earlier than 1970-01-02. A window may run a minute past 30 days,
  so a `since` 30 days before the caller's now passes when that clock runs behind the
  server's. A label's credit time is a whole second. An `until` inside a second takes
  that whole second, so a label credited a moment ago is in the window, and a `since`
  inside a second takes that whole second too. A window's read runs under the
  caller-shaped caps (`LOOM_CH_CALLER_SHAPED_MAX_ROWS_TO_READ` and its time and memory
  peers); one that needs more answers 422, and a later `since` or a shorter window
  narrows it.
- The caller's own labels are those posted under any spelling of its principal: the
  token's subject and each spelling the directory ties to it (the login handle and the
  verified email), in any case, since a label stamps its principal case-folded. Names
  equal under Unicode case folding (`straße@example.test` and `strasse@example.test`)
  are one principal, and their labels are retracted and erased together. The principal
  keeps the token's kind: a person's own token reaches the labels it posted
  (`human:<spelling>`), and a service-account token under the person's spelling, such as
  a trusted caller acting for them (`X-Loom-On-Behalf-Of`) or a
  `loom mint-token --subject <spelling>` token, reaches every `process:<spelling>` label
  of that person, whichever such token posted it. A person's own token does not reach
  the labels a trusted caller whose token is a service account posted for them. The
  trusted caller acting for them, or a namespace admin through `run_id`, cancels those;
  the window form keeps to the caller's own labels, an admin's too. A user erasure
  reaches every kind, an end user's (`human:user:<id>`) among them. When the server
  cannot read those spellings, the call answers `503 BACKEND_UNAVAILABLE` with "the
  caller's spellings could not be read; retry", writes nothing, and is safe to resend.
- A second call over the same labels finds them at zero and writes nothing. A compensating
  event carries the cancelled label's credit time, so a window that covers a run already
  retracted finds that run at zero too.
- A namespace's retractions run one at a time across all server processes, so two over
  overlapping labels never both cancel them. A call that waits more than 10 seconds for
  another answers `503 OVERLOADED`, writes nothing, and is safe to resend. An erasure step
  that rewrites the namespace's usage events holds the same claim for as long as its
  mutation runs, up to `LOOM_ERASURE_MUTATION_WAIT_S`, so a call meanwhile answers
  `503 OVERLOADED` too. A call that finds an update or delete of the usage events still
  running, such as an erasure's in any namespace, answers `503 BACKEND_UNAVAILABLE` with
  `Retry-After: 5` and "a mutation of the usage events is still running; retry", and
  writes nothing too: while one rewrites a label's run and principal, a read could see the
  label without its cancellation. A call that cannot read ClickHouse's mutation queue
  answers the same way with "could not read the mutation queue; retry". A mutation that
  keeps failing stays in the queue, so every call that is not a dry run answers `503`
  until an operator fixes its cause or ends it, as
  [retention and erasure](/docs/features/memory/retention-and-erasure#a-mutation-that-keeps-failing)
  describes.
- `dry_run=true` reports the counts and writes nothing, without waiting for another
  retraction in the namespace. One call cancels at most 5,000 labels; `more=true` says
  some are left, and the next call continues. A dry run counts at most the first 5,000
  labels and says so with `more=true`; since it cancels none, repeating it counts the same
  ones.

```python
from datetime import UTC, datetime, timedelta

run_id = "..."  # the id agent.run.begin (run.begin) returned
await agent.run.retract_credit(run_id)  # every label of the run the caller may cancel
# The caller's own labels credited in the last week, counted but not cancelled:
week_ago = datetime.now(UTC) - timedelta(days=7)
preview = await agent.run.retract_credit(since=week_ago, dry_run=True)
print(preview["used_retracted"], preview["events_written"], preview["more"])
```

A retraction reaches only labels that carry a principal, never the server's own usage
events (recalls, an answer's citations); a label with no principal stamped on it is out of
reach. It leaves:

- the `evidence_count` and `recall_count` kept on the memory row, which only ever grow and
  which the list score reads. `memory.get` shows the usage totals' evidence count instead
  while it is above zero, so it drops as labels are retracted, and shows the row's count
  again (the most it reached, plus one for the write) once a retraction brings the
  totals to zero;
- a quarantine that negative outcomes triggered;
- the run row's `memories_used`, and the procedure runs `run.complete` recorded from it;
- a label still in another server process's write buffer, which lands within a second, and
  a label posted while the call runs, unless it lands before the call reads; a later call
  cancels either. The process that serves the retraction lands its own buffer first, so
  the call covers every label of an op that answered on that process before the call
  arrived; when a label of that buffer cannot land, or has not landed within what is left
  of the op's latency budget (never less than
  `LOOM_CH_BATCHED_INSERT_BACKGROUND_WAIT_MAX_MS` plus 0.1 seconds, what an insert already
  sending takes to answer), the call answers `503 BACKEND_UNAVAILABLE` before it reads or
  writes, and is safe to resend;
- the labels posted with a token narrowed to one user, such as an end user's token: such a
  token is refused `run.retract_credit`. A namespace admin still cancels a run's labels,
  and a token of the same principal that is not narrowed cancels them in either form. A
  user erasure takes an end user's principal and run off the labels their token posted;
- the labels a user erasure scrubbed: their principal is `<erased>`, and their run id
  too when they have one, so neither form can retract them, and their credit stays in the
  totals.

The 24-hour agent-label gauge sums the net, so it drops by what a retraction cancels, and
reads below zero when the cancelled labels were posted before its window.

## Reflections

`run.complete(reflection=...)` records `what_worked`, `what_failed`, `assumptions`, `lessons`, `improvements` (up to
20 items each), a `confidence` and the `evidence` keys the lesson rests on. It is stored as one memory of type
`reflection` under `reflection:<run_id>`:

- it is embedded, so a later run can find it with `memory.search(memory_type="reflection")`,
  but it is left out of unfiltered search and `memory.ask`;
- `what_failed` and `lessons` need at least one `evidence` key (a 422 otherwise);
- it expires after `expires_in_days` (default 90, `0` = never) unless `memory.verify`
  or a positive outcome renews it;
- a run opened with `role` (planner, executor, critic, or your own word) tags its
  reflection `role:<role>`, so a same-role agent's `memory.search(role=...)` prefers it.

## What happens to the rows a run wrote

`retain` on `run.complete` decides the fate of the memories written under the run:

| `retain`         | Effect                                                                                                                                        |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `keep` (default) | Nothing changes.                                                                                                                              |
| `demote`         | Their confidence is lowered now.                                                                                                              |
| `expire`         | An expiry `LOOM_MEMORY_RUN_COMPLETE_EXPIRE_DAYS` out (default 7) is set with `on_expire=demote`; the `memory_expiry_sweep` worker applies it. |

Pinned, verified, promoted, locked, episodic and reflection rows are kept whatever the
mode, and no mode tombstones anything. The default comes from
`LOOM_MEMORY_RUN_COMPLETE_RETAIN`; an MCP session's implicit run always keeps, since
the transport that closes it cannot judge the work.

## Graded runs

`status` says the run ended; a grade says whether its result held up. A grade often arrives days later, when CI
passes or a reviewer rejects the pull request. `run.grade` takes `grade` (`pass` or `fail`), a `source` (`maintainer`,
`ci`, `reviewer`, … free text), a `reason` and a `ref` (a URL, a finding key, a check run
id), addressed to one `run_id` or to every closed run of a `session_id` (for example
`pr_1234`). A regrade replaces the verdict; the same verdict from the same source changes
nothing. Active runs are skipped.

Every memory in a graded run's `memories_used` is counted against the grade. Those
counts are what `memory.proposals` shows beside each fact on trial (a
`memory.set(proposed=true)` row). Pass counts mark a proposal ready for independent human review. When the namespace owner
sets `proposal_policy.mode` to `auto`, failed counts can reject a proposal. Acceptance
requires an independent human administrator using `memory.proposal_decide` with the hash
of the reviewed content. See [writing memory](/docs/features/memory/writing).

`run.list(grade="ungraded")` lists the closed runs still owed a verdict.

## MCP sessions

An MCP session gets an implicit run without asking: its first run-scoped tool
call begins one, and `DELETE /mcp` or the `mcp_session_run_sweep` worker closes
it (see [MCP](/docs/reference/mcp)). A call is run-scoped when its op takes a
`run_id` (`run.*` and `code.*` apart), or when it is a read that writes a
[read receipt](/docs/architecture/read-receipts), so a session that only reads
documents has a run too. A write that names no run carries the session's run
(`working_memory.*` and `conversation.update` apart, where `run_id` scopes or
binds the row), and a read is labelled with it: its receipts, its request
ledger row and its exposure row are filed under it.
[Reading the table](/docs/architecture/read-receipts#reading-the-table) names
the calls that are filed otherwise, and those that begin no run.

`run.begin` over MCP opens a second run under an id of its own, which the
agent passes on its writes. A `run_id` on a read filters to the run's own rows,
so the session's reads name none and stay under the session's run, and the row
of the run that was opened names that run in `metadata.session_run`. The
receipts under the run's own id and under its session's run, made while the run
was open, are therefore the session's reads of that time filed under either id;
a session read filed under `-` or under another run it names is not among them
([reading the table](/docs/architecture/read-receipts#reading-the-table)). A
`run.begin` sent again with the same `run_id` keeps the session it was first
opened in, unless it is sent from another MCP session, which it then names.

That is the session's reads filed under either id, which is not always the run's:

- Two runs open at once in one session name the same session run, so each is
  read with the other's reads.
- A run opened again after it closed keeps its first start (a begin sent again
  after `run.complete` clears the close), so it is read with the session's
  reads made while it was closed.
- A client that reconnects under a new `Mcp-Session-Id` reads under an id the
  run's row does not name.
- A begin sent again from another MCP session replaces the stored id, so the
  first session's reads are no longer tied to the run.

Two runs record no `session_run`. One is opened in a session that has no run:
its calls send no `Mcp-Session-Id`, or its token has no default namespace. The
other is opened over HTTP while its agent reads over MCP: those reads are under
the session's run, and nothing ties them to the run. The coding-agent plugins
work this way: a hook calls `run.begin`, the model calls the MCP tools.

The sweep closes an active run with
`environment='mcp'` and `metadata.implicit` true whose id is `mcp-` plus 40 hex
characters (the shape only the transport makes). It closes one once no call of
its token (of anyone, for a run that records no token) reached it within
`LOOM_MCP_SESSION_RUN_IDLE_SECONDS`. The run sits in the caller's default
namespace, so what its readers see stays there: its goal is the label
`mcp session (<agent>)`, never a call's text (a read's query may reach any
namespace the caller reads), and `memories_written` lists the writes in that
namespace only (the others still carry its `run_id`). Closing it judges nothing:
its outcome is `none` and its memories are kept whatever the server's default
retain mode, so two closes racing for it (the sweep on two hosts, a `DELETE`)
at worst write the same completion twice.

How the run spans web processes. Its id is a hash of the caller's org, the
token's subject and the `Mcp-Session-Id`, so every process of the server names
the same run for the session and no other token can name it by sending the same
session id. A process registers the run on the session's first admitted
run-scoped call and writes the begin row in the background (an awaited insert
would hold that call for seconds on ClickHouse Cloud); a call the gates refuse
writes no run row. Two processes that both find no row each write a first begin,
and the earlier start and its owner win (a first begin's row version counts down from
its start; every later write supersedes it). Each process checks a cached run with the ledger at most once
a minute and re-opens it when a `DELETE` or the sweep closed it in the meantime.
A `DELETE` closes the run whichever process it reaches, by its id; the close
counts every write under that id, whoever closes it. A `DELETE` that reaches
another process before the begin row has landed finds nothing to close, and the
begin then lands an open run that the sweep closes once it goes idle: a short
retry would not cover a begin that takes seconds, and would delay the `DELETE`
of every session that never took a run. A re-opened run keeps its original
`started_at`, so a run closed by the sweep and re-opened later reports a
`duration_ms` counted from the session's first call, gaps included. A check that
finds no row at all, because an erasure deleted it, begins a new run started then,
so no run dated before the erasure comes back.

## Ids the server reserves

Two shapes of `run_id` are the server's, and `run.begin` hands out neither:

| Shape                        | The row under it                                                                                |
| ---------------------------- | ----------------------------------------------------------------------------------------------- |
| `mcp-` and 40 hex digits     | An MCP session's run, which the transport opens and closes ([MCP sessions](#mcp-sessions)).     |
| `cur-` and 10 decimal digits | A curator pass, which only the server writes. The digits are the pass's start in epoch seconds. |

A `run.begin` that supplies an id of either shape opens a run under an id the server
makes for that caller, as it does for an id another user holds. The answer carries the
id to use, and the same begin sent again lands on the same run.

A curator pass's id is refused whether or not a row holds it. `run.complete` and
`run.grade` on one answer as for a run that does not exist, and a grade addressed by
`session_id` leaves a pass's row out. `run.get` and `run.list` serve the row to whoever
may read the namespace's runs. The row is no agent's work, so three reads leave it out:
`run.list(grade="ungraded")`, the run count of `namespace.inventory`, and the runs
manifest of a context pack.

## A link to a run

In the dashboard, `/runs?namespace=<namespace>&run=<run_id>` opens that run's replay. The
address holds the namespace and the run id, and nothing the run recorded.

The Runs page keeps the open run in its address: opening a run writes `run`, closing it
removes it, and neither adds a history entry. A reload reopens the run, and so does Back
from a document or the recall history opened from it. Switching namespace removes `run`.

The page reads the run with `run.get` under the reader's own token, whether or not the
list shows it. A run id the namespace holds no run for and a run the reader may not read
show one notice, "No run with this id in this namespace.", and neither prints the id the
address carried. A namespace the reader holds no role on opens the page that says so, as
for [every address](/docs/features/dashboard#a-pages-address-and-its-namespace).

## Operations

| Operation                                                    | Role   | Does                                                                                                                                                                                                                                                                                                                                                                                   |
| ------------------------------------------------------------ | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `run.begin`                                                  | writer | Open a run: `goal` (required), `user_request`, `expected_outcome`, `run_id` (empty or `-`: minted), `session_id`, `role`, `model`, `metadata`. Re-sending the same `run_id` replaces the row and keeps its `metadata.session_run`, or names the calling MCP session's run when sent from another; a supplied id [the server reserves](#ids-the-server-reserves) gets an id of its own. |
| `run.complete`                                               | writer | Close it once: `status`, `memories_used`, `memories_delivered`, `recalled_keys`, `outcome`, `reflection`, `retain`. Not idempotent: completing twice appends usage events twice.                                                                                                                                                                                                       |
| `run.get`                                                    | viewer | One run with its live derivations.                                                                                                                                                                                                                                                                                                                                                     |
| `run.list`                                                   | viewer | One page of runs, filtered by `agent`, `session_id`, `status`, `grade`, `q` and `memory_activity` (`with` keeps runs that relied on or wrote a memory, `without` the hollow ones; filters apply before `limit`).                                                                                                                                                                       |
| [`run.reliance`](/docs/reference/operations/run#runreliance) | viewer | What a run was served, at which revisions, and what its client reported relying on, with one state per item ([what a run read](#what-a-run-read)).                                                                                                                                                                                                                                     |
| `run.grade`                                                  | writer | Grade a closed run or a session's runs `pass` / `fail`.                                                                                                                                                                                                                                                                                                                                |
| `run.retract_credit`                                         | writer | Cancel the `used`, `evidence` and `harm` events of a run's labels, or of the caller's labels in a window (`since`, `until`), with compensating events; `dry_run` reports only. Idempotent.                                                                                                                                                                                             |

`run.list` pages with `order_by` (start time, duration or memories relied on, each
ascending or descending; `started_desc`, newest first, by default) and `offset` (at most
100,000). `q` keeps runs whose goal, run id or agent holds the text, in any case. `total`
counts every run the filters match, and is null on a full page after the first, where the
page alone cannot tell it.

The full field lists are in the [operations reference](/docs/reference/operations#run).
`memory.outcome_run` records one helped / hurt outcome for every memory recalled under a
run, for callers that grade in bulk rather than naming keys.

## Example

The Python SDK's `run.scope` opens the run on entry and closes it on exit. The keys a
`memory.ask` answer cited inside the block, plus any passed to `used()`, become
`memories_used`. Once `delivered()` names the keys the client put in front of the model,
only the used keys among them and the cited ones earn credit: the scope sends just those
as `memories_used`, so a server that predates `memories_delivered` credits the same
keys, and `run.completed["undelivered"]` counts the rest. An exception closes the run
as `failed` (outcome negative) and then propagates. Writes inside the block carry the
run's id.

```python
from loom import Agent

async with Agent(org="acme", namespace="support", agent="triage-bot") as agent:
    async with agent.run.scope(goal="Answer ticket 4411: refund policy for annual plans") as run:
        answer = await agent.memory.ask("what is the refund policy for annual plans?")
        run.used("policy/refunds/annual")  # relied on beyond what the answer cited
        run.delivered("policy/refunds/annual", "policy/refunds/monthly")  # what the prompt showed
        run.final_response = answer["answer"]

    replay = await agent.run.get(run.run_id)
    print(replay["run"]["status"], replay["memories_written"], replay["recalled"])

    # Later, once the customer confirmed the answer was right:
    await agent.run.grade("pass", run_id=run.run_id, source="support-lead")
```

Over HTTP the lifecycle is two calls:

```bash
curl -sX POST "$LOOM_BASE_URL/v1/run.begin" -H "Authorization: Bearer $LOOM_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"org":"acme","namespace":"support","agent":"triage-bot","goal":"Answer ticket 4411"}'
# → {"run_id":"…","status":"active","started_at":"…","next":"…"}

curl -sX POST "$LOOM_BASE_URL/v1/run.complete" -H "Authorization: Bearer $LOOM_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"org":"acme","namespace":"support","run_id":"…","status":"completed",
       "memories_used":["policy/refunds/annual"]}'
```

`Agent(auto_run=True)` (or `LOOM_AUTO_RUN=on` in the client's environment) opens a run
lazily on the first memory-plane call, threads every later call through it, and
completes it when the `Agent` closes, with outcome `none`, so it never credits or charges anything. It is off by
default because a write under a run is scoped to it: a restatement of another run's row is stored as a `duplicate`
rather than merged.

## Settings

| Setting                                                       | Effect                                                                                                                |
| ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `LOOM_MEMORY_RUN_COMPLETE_RETAIN`                             | The `retain` mode when a call does not name one (`keep`).                                                             |
| `LOOM_MEMORY_RUN_COMPLETE_EXPIRE_DAYS`                        | How far out `retain=expire` sets the expiry (7 days).                                                                 |
| `LOOM_SEARCH_TRACE_LOG_ENABLED`                               | Records every search under its `run_id`, which `recalled` is derived from. Off by default because it logs query text. |
| `LOOM_USAGE_FOLD_ENABLED`                                     | The `usage_fold` worker that turns used / evidence / harm events into ranking.                                        |
| `LOOM_MEMORY_SEARCH_REINFORCEMENT_WEIGHT`, `…_HALF_LIFE_DAYS` | How much, and for how long, reliance lifts a row in search.                                                           |

See [configuration: dedup and expiry](/docs/reference/configuration#dedup-and-expiry),
[workers](/docs/reference/configuration#workers) and
[MemorySearch](/docs/reference/configuration#memorysearch).

## Limits

- `memories_used` and `recalled_keys` take at most 500 keys each; `goal` at most 2,000
  characters.
- A key in `memories_used` that does not resolve to a live row earns nothing;
  `used_applied` in the response counts the ones that did.
- `run.complete` is not idempotent. A retried completion double-counts usage events;
  complete once. `run.retract_credit` cancels all of the run's credit, not only the copy.
- The SDK's `run.scope` writes the ledger best-effort: a failed `run.complete` never
  masks the block's own exception, so a run whose completion failed stays `active`.
- `turns` and `cost_usd` are 0 when the run has no `session_id` or the client does not
  report turn usage. They count only the turns made while the run was open.

## Related

- [Trace and resume long runs](/docs/guides/trace-and-resume) — checkpoints in working
  memory keyed by `run_id`, and how to trace what a run did.
- [Search and ask](/docs/features/memory/search-and-ask) — how reinforcement enters ranking.
- [Tasks and decisions](/docs/features/tasks-and-decisions) — `decision.outcome` credits the memories
  a deciding run relied on.
- [Memory architecture](/docs/architecture/memory-architecture) — the usage-event fold
  and the tables behind it.
- [Read receipts](/docs/architecture/read-receipts) — the revision of an item a run's
  read carried.
