# Build on the Memory Bank

> How a workflow learns from the vault's Memory Bank and contributes to it — workflows write cubbies, curators propose, people accept, workflows read what was accepted.

Source: https://developers.manykind.ai/vaults/build-on-the-memory-bank/

A workflow never writes the [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/) itself. It
writes its own [cubby](https://developers.manykind.ai/agents/building-blocks/cubbies/). A **curator**, an
agent whose connection the vault owner gave the harvester or analyzer role,
reads that cubby and **proposes** records. A person **accepts** or rejects
each proposal in ROC. Workflows then read what was accepted.

```text
workflow run ──writes──▶ cubby (raw, working rows)
                              │ read by
                              ▼
          analyzer (measured counts) / harvester (proposals)
                              │ ctx.memory.proposeMetric / ctx.memory.propose
                              ▼
                 Memory Bank: proposed records
                              │ a person accepts in ROC
                              ▼
                 Memory Bank: accepted records ──read by──▶ workflows, LLM agents, ROC Ask
```

## Rules

- **A workflow writes its cubby, never the bank.** A vault that enforces
  curators refuses any other agent's bank write with `403`. On a vault that
  doesn't, the write lands as an accepted record nobody reviewed, which is
  worse. `mk build` warns on every `remember` and `relate` step
  (`memory-write-from-workflow`).
- **A bank reader never joins back to a cubby.** Anything a reader needs (dates,
  stages, labels) goes into the record or its `props` when the curator writes it.
- **Only a person accepts.** Accepting or rejecting stamps the record with
  `reviewed_by` and `reviewed_at`. A record that is accepted but has no stamp
  was not accepted by a person.
- **Measured numbers are never accepted.** An analyzer's `metric:` and `obs:`
  records stay proposed. Show them as "measured, not reviewed". A claim drawn from
  them is a separate harvester proposal, and that claim is what a person accepts.

## Read the bank from a workflow

By default every read returns **accepted** records only, in the scopes your
connection holds, up to the privacy ceiling of the person who started the run.
Proposed records are invisible unless you ask for them.

| Need | Use |
|---|---|
| Accepted knowledge by keywords, in a workflow | `recall` step with `match` |
| Accepted records of one type or domain, newest first | `recall` step with `types` or `domains` and no `match` |
| The same from code | `ctx.memory.search(match, opts)`, `ctx.memory.list(opts)` |
| One record by id | `ctx.memory.record(id)`: one typed record or `null`, **any status** |
| An analyzer's counts | `ctx.memory.metrics(opts)` / `ctx.memory.metric(id)`: numbers plus the measured label |
| An LLM step that searches iteratively | the vault's MCP tools `search` → `get` (see [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/#from-an-llm-agent-mcp)) |

```ts
// accepted principles and findings about sales, with their props
const hits = await ctx.memory.search("pricing objection", {
  domains: ["sales"],
  types: ["principle", "finding"],
  include: ["props"],
  limit: 10,
});

// one record reached by id: check the status before acting on it
const rec = await ctx.memory.record(hits[0].id);
if (rec?.status === "accepted") {
  // act on rec.body / rec.props
}

// measured counts: show them as measured, never as accepted knowledge
const { records } = await ctx.memory.metrics({ domain: "sales" });
for (const m of records) console.log(m.label, m.id, m.values);
```

- `record()`, `neighbours()` and the MCP `get` return records **of any status**.
  Check `status` before you act on a record you reached by id or by edge.
- Pass `statuses: ["accepted", "proposed"]` only to show unreviewed work, or to
  avoid proposing it twice.
- `domains`, `types` and `scope` only narrow. An ungranted scope returns no
  rows, never an error.

**Cite what you used.** Store the record ids a decision relied on in your cubby
row, next to that decision (for example a `used_record_ids` column). The platform
records *that* a run read a record. Only your cubby says *which decision* it
informed, and that is what an analyzer needs to measure whether the advice helped.

**Read narrowly.** When the vault records reuse, `search`, `get` and filtered
`list` count as reuse of the records they return, up to 200 per run. Unfiltered browsing and counts do not.
Search narrowly, then `record()` what you actually use.

## Write cubby rows a curator can use

Curators read your tables by configuration. Shape them so that configuration
is short.

1. **One row per subject, keyed by a stable subject key**: a lead, a
   candidate, an incident, a campaign. Use a key that survives renames and
   re-imports, never a display name or a row id. Every workflow that sees the
   same subject uses the same key.
2. **Record the run on every row**: `run_id` (`{{ $runId }}`), `workflow`,
   `workflow_version`, and the version of the settings that shaped the
   decision. The curator copies the run into the record it proposes
   (`props.origin_run = "run:<runId>"`), which is how outcomes are attributed
   back to the workflow run that produced them.
3. **Keep observation and outcome apart.** What the workflow saw and decided
   is one table. What happened later goes in an **append-only** outcome table
   (`subject_key, outcome, value, source, at`), never as an update of the
   decision row.
4. **Timestamps that mean something.** Set `at` to when it happened, in
   RFC 3339 UTC. Add a `captured_at` that every pass sets, so a curator can tell
   "the writer stopped" from "nothing happened".
5. **Signals as columns, not prose.** Counts need categorical columns with a
   closed vocabulary. Free text can't be measured and never goes into the bank.
6. **Mark test data** with a column (`is_test`) rather than relying on lists
   of ids to exclude.
7. **Put the tables where the curator can read them.** A curator in the same
   Agent Service reads your cubby directly. A curator in another service reads
   the scope's shared cubby: write it with `ctx.workspace(alias)`.

## Write a curator

Pick the role by what it writes. Never give one connection both roles.

| Role | Writes | Method |
|---|---|---|
| **Analyzer** | measured counts and their evidence | `ctx.memory.proposeMetric`, `ctx.memory.proposeObservation` |
| **Harvester** | statements a person should accept: principles, findings, decisions, conclusions | `ctx.memory.propose` |

### Ids

An id is the record's idempotency key: the same subject gives the same id on
every run.

| Record | Id |
|---|---|
| Harvester, revision 1 | `<type>:<key>` |
| Harvester, revision n ≥ 2 | `<type>:<key>~<n>` |
| Analyzer metric | `metric:<analyzer>:<segment>@<period>`, where period is `YYYY-MM-DD` or `YYYY-Www` |
| Analyzer evidence | `obs:<analyzer>:<subject>@<config_version>` |

- `<key>` is `[a-z0-9][a-z0-9._/-]*`, at most 120 characters, and unique per
  type in the vault. When a type is used in several domains, start the key with
  the domain: `decision:sre-<slug>`.
- Never put a review state (`proposal:`, `accepted:`) or a scope in an id.
  Status and scope are fields, and changing them never changes the id.
- `run`, `outcome`, `person` and `domain` records are the platform's.

### Propose

```ts

const inputs = { rows: evidenceIds, config: CONFIG_VERSION };
const res = await ctx.memory.propose({
  id: `finding:sales-${slug}`,
  type: "finding",
  title: "Referral leads convert twice as often",
  body: "Across 4 weeks, referral leads reached a meeting at 2.1× the rate of outbound.",
  scope: "sales",
  domain: "sales",
  privacy: "internal",
  props: {
    source: "cubby:sales/_shared/outreach",
    source_hash: sourceHash(inputs),
    origin_run: `run:${originRunId}`,
  },
  derivedFrom: metricIds,
});
// res.outcome: "written" | "revised" | "unchanged" | "decided"
```

`propose` does what a curator must, so you don't hand-write it:

- It always writes `status: "proposed"`. There is no way to send another status.
- It **reads first**:
  - a proposed record is rewritten in place, or left alone when nothing changed;
  - a rejected or superseded record is never touched;
  - an accepted record is revised (`<id>~n+1` with a `supersedes` edge to it)
    only when `props.source_hash` changed.
- `source_hash` fingerprints the **inputs** the curator read: the source rows and
  the config that shaped the claim. Never hash generated text, or reworded
  output would mint a new revision every run.
- It fills `props.run_id`, `props.curator` (`<agent>@<version>`) and
  `props.revision` for you.
- It **reads every write and edge back** and throws `MemoryError` with code
  `NOT_LANDED` when the bank acknowledged a write it did not keep. The bank
  answers a write the same way whether or not a row changed, so this read-back is
  the only proof.

`domain` is required (an upsert without it clears it), and so are
`props.source` and `props.source_hash`. Edges point from the new record:
`claim --derived_from--> evidence`, `new --supersedes--> old`,
`record --about--> topic`.

### Errors

Every `ctx.memory` method throws `MemoryError`.

| `code` | Means | Do |
|---|---|---|
| `WRITE_REFUSED` | The connection may not write the bank (no curator role), or broke its role's rules | Check the role; a workflow writes its cubby instead |
| `SCOPE_DENIED` | The target scope isn't one the connection holds | Connect the agent in that scope |
| `NO_INITIATOR` | The run has no person behind it, so it may read or write nothing | Start it from a schedule or a person, not a bare webhook |
| `NOT_LANDED` | Acked but not kept: an id held in a scope you can't see, or a decided record | Read `err.current`; change the id or leave it |
| `DECIDED` | `propose` with `onDecided: "throw"` hit a decided record | Expected when a person already decided it |
| `INVALID` | Rejected before any request: id grammar, a missing `domain` or `source_hash` | Fix the input |
| `BAD_REQUEST`, `HTTP` | Any other server refusal | Read the message |

A record or edge above your own privacy ceiling is refused with `403`
`PRIVACY_ABOVE_CEILING` (`err.serverCode`). For an agent, the ceiling is the run
initiator's.

## Register a curator

1. Deploy the curator and [connect](https://developers.manykind.ai/vaults/connections-and-consent/) it in the
   scopes whose cubbies it reads and whose records it writes.
2. The vault owner or an org admin sets the role with the Vault SDK:

   ```ts
   const conn = (await vault.agents.list()).find((c) => c.agentId === agentId);
   const updated = await conn!.setHarvester(true);   // or: conn!.setAnalyzer(true)
   console.log(updated.harvester, updated.analyzer);
   ```

   A connection holds one role. Setting a second answers `409 ROLE_CONFLICT`.
3. Read the role back (`harvester` / `analyzer` on `vault.agents.list()`), and
   again after every reconnect or upgrade.
4. Give runs an initiator: a scheduled run runs as the member who connected the
   agent, and an event-driven run runs as the publisher. A run with no initiator
   reads and writes nothing.

## Classify

- `privacy` is required on every record and edge and is never defaulted. Choose
  by the most sensitive thing the record, or its existence, reveals. An edge
  carries its own privacy.
- Aggregates are usually `internal`. Per-subject evidence is `internal` or `private`.
- Build titles and bodies from counts, slugs and config values. Never copy names,
  messages or emails from cubby rows into the bank.
- Scope says where a record lives and who may see it; domain says what it is
  about. Write into the scope the readers hold, and filter by domain when you read.

## Test

| Layer | How |
|---|---|
| Unit | `testPlatform` from `@manykind-ai/testing`. Its bank is gated by scope, privacy and status, and enforces the curator policy: an ordinary connection's write is refused, and a harvester's lands proposed. Give a connection a role with `memory.connections[agentId].role`. Use `platform.memory.accept(id)` to play the person who accepts. |
| Prove the gate | In a test, write from a connection with no role and assert the `WRITE_REFUSED`. A test that only ever passes proves nothing. |
| Read path | After a curator run, search with `statuses: ["proposed"]`. Accept one in ROC, then confirm the workflow's `recall` returns it. |

## Avoid

- A `remember` or `relate` step in a workflow.
- Mirroring cubby rows into the bank one record per row.
- A reader that looks up names, stages or ids in a cubby at read time.
- Trusting a write's acknowledgement. Read back, or use `propose`.
- Accepting a metric, or showing a measured count as accepted knowledge.
- Hashing generated text into `source_hash`.
- Writing above the ceiling of the person the run acts for.
- Paging the whole bank "just in case": it spends the run's reuse budget on noise.
- Assuming a webhook-triggered run can read the bank. Check that it has an initiator.

## Limits

| Limit | Value |
|---|---|
| `search` / `list` page | default 50, at most 500 |
| `types` filter | at most 10 |
| `domains` filter | at most 20 |
| Record `props` | 16 KiB |
| Id key | 120 characters |
| Reads counted as reuse | 200 per run |

## Related

- [Next: Connectors](https://developers.manykind.ai/vaults/connectors/)
- [Memory Bank](https://developers.manykind.ai/vaults/memory-bank/)
- [Cubbies](https://developers.manykind.ai/agents/building-blocks/cubbies/)
- [Workflow steps](https://developers.manykind.ai/agents/workflows/steps/#memory)
- [Connections and consent](https://developers.manykind.ai/vaults/connections-and-consent/)
