From abff4b6c1eef4e779a259db38414a711c940eb72 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 21:26:53 +0000 Subject: [PATCH 1/5] memory.verify takes the content hash the caller read and refuses to attest or revoke other content An attestation records who checked which content, and the content is the value the row holds when the server reads it. An edit that lands between the caller's read and the call is attested unseen. `if_match_sha256` on `memory.verify` names the `content_sha256` of that read. The handler compares it with the live hash before the revoke and no-op branches and answers 409 `PRECONDITION_FAILED` with `current_sha256` on another hash: no version row, no embeddings mirror. An empty field checks nothing: a call without it attests the row as the server reads it. The dashboard's Verify and Remove verification address the row the drawer shows and send the hash of the value shown; a 409 reads the memory again. `MemoryClient.verify` takes the field, and the generated SDKs and reference pages carry it. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/architecture/memory-architecture.md | 5 +- docs/architecture/rolling-upgrades.md | 4 +- docs/concepts/memory.md | 3 +- .../features/memory/history-and-provenance.md | 11 ++ docs/features/memory/writing.md | 6 +- docs/reference/errors.md | 2 +- docs/reference/operations.md | 2 +- docs/reference/operations/memory.md | 3 +- frontend/src/api.memory.test.ts | 61 ++++++++- frontend/src/api.ts | 14 +-- .../MemoryInspector.lifecycle.test.tsx | 54 ++++++++ frontend/src/components/MemoryInspector.tsx | 15 ++- sdk/go/wire/models.gen.go | 21 ++-- sdk/python/loom/memory.py | 6 + sdk/python/loom/ops.py | 6 +- sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 4 +- sdk/rust/src/wire_models.rs | 11 ++ sdk/typescript/src/generated/ops.ts | 1 + server/memory/api/models_crud.py | 8 +- server/memory/app/verify.py | 11 ++ server/transport/mcp_descriptions.py | 5 +- tests/integration/test_memory_verify.py | 36 ++++++ tests/unit/session_content_senders.json | 2 +- tests/unit/snapshots/sdk_public_api.json | 3 +- tests/unit/test_memory_verify.py | 119 ++++++++++++++++++ tests/unit/test_sdk_write_kwargs.py | 10 ++ 26 files changed, 384 insertions(+), 39 deletions(-) diff --git a/docs/architecture/memory-architecture.md b/docs/architecture/memory-architecture.md index 4652aa52eb5..147390ea5d5 100644 --- a/docs/architecture/memory-architecture.md +++ b/docs/architecture/memory-architecture.md @@ -1326,7 +1326,10 @@ usage fold's counters on `memory` are batched lightweight updates; see Under the ClickHouse authority, every memory version insert holds a Keeper fence per identity key. `memory.lock`, `memory.unlock` and `memory.verify` check that the source row is still the head inside the fence, and answer 503 `ADMISSION_CONTENDED` with -no version written when it moved. All value inserts take the same fences, including +no version written when it moved. `memory.verify` first compares `if_match_sha256`, when +sent, with the hash of the head it read and answers 409 `PRECONDITION_FAILED` on +another; the fence covers a head that moves after that comparison. All value inserts +take the same fences, including unconditional writes and batches, so the check and insert cannot interleave with another replica's version insert. A re-read outside the fence provides no such guarantee. The check compares values and metadata as well as versions, since writers can draw diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index fa2cefea598..17af261e506 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -179,7 +179,9 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline behind another memory, and the `relations` of `memory.set`, `memory.update` and `memory.update_by_id` are dropped there, so that write graphs none of the facts it names. `memory.get_by_id`'s `omit_high_value` does not hold there either: N-1 answers - a `high` row with its value and hash, and audits that read as a sensitive one. N's + a `high` row with its value and hash, and audits that read as a sensitive one. + `memory.verify`'s `if_match_sha256` does not hold on an N-1 replica, which attests or + revokes the row it reads. N's conflict resolver does not read the `memory.unsupersede` record of an Undo made on an N-1 replica, or before the upgrade: it carries neither the restored hash nor the restore version. The restored row then reads as a statement made at the Undo, diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 178414698a2..cbaee98d1a8 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -1033,7 +1033,8 @@ so `memory.ask` keeps unattested `external` rows out of its synthesis 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, + hash. A caller that sends `if_match_sha256` attests only the content it read. 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. diff --git a/docs/features/memory/history-and-provenance.md b/docs/features/memory/history-and-provenance.md index f4115ed403b..16044144433 100644 --- a/docs/features/memory/history-and-provenance.md +++ b/docs/features/memory/history-and-provenance.md @@ -120,6 +120,17 @@ actor from the caller's token and the content hash they attested. Address the ro `memory_id`, or by `namespace` and `memory_key` with the writer identity. It needs writer on the row's namespace. +Send `if_match_sha256`, the `content_sha256` of the read being attested, and the call +attests only that content. A row that holds other content answers 409 +`PRECONDITION_FAILED` with `current_sha256` and writes nothing: read the row again and +attest what it says, never the returned hash unread. `revoke=true` takes the same +precondition. Without the field the call attests the row as the server reads it, so an +edit that lands after the caller's read is attested unseen. + +```bash +loom call memory.verify memory_id= if_match_sha256= +``` + `memory.get` and `memory.get_by_id` return `verification`, derived from the stored hash and the row's current one: diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index b4e1cdd54db..2216ecf7613 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -145,8 +145,10 @@ async with Agent(org="acme", namespace="support", agent="triage-bot") as agent: ... # re-read (the error carries current_sha256), decide, retry ``` -`memory.update`, `memory.update_by_id` and `memory.move` (source row) accept the same -precondition. The Python SDK coalesces a burst of `set` calls from one identity into one +`memory.update`, `memory.update_by_id`, `memory.move` (source row) and +[`memory.verify`](./history-and-provenance.md#attestation-memoryverify) (the row being +attested or revoked) accept the same precondition. The Python SDK coalesces a burst of +`set` calls from one identity into one `memory.bulk_set` (from the third set inside 200 ms); a coalesced result carries `coalesced: true` and no `content_sha256`. A set with `if_match_sha256` is never coalesced. diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 3720fd75040..2e67dd73393 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -172,7 +172,7 @@ resend are in each page's Errors section. Each op's kind is in the | `AUTH_INSUFFICIENT` | 403 | The token's role or namespace access does not cover the op (over MCP the result carries `required_role`). The assistant's refusals carry `reason`: `org_wide`, `narrowed` or `token_expires_soon` with `left_s` ([the assistant's refusals](../architecture/assistant.md#each-callers-own-identity)). | A namespace that does not exist is refused with the same code as one the token may not read, so check the name against `namespace.list_mine` first. Then compare the op's role in the [operations reference](./operations.md) with the token (`GET /v1/whoami`) and ask a namespace admin for a grant. | | `POLICY_FORBIDDEN` | 403 | A history-policy rule denied the call (`decision`, `determining_rules`, `errors`) with `LOOM_POLICY_MODE=enforce`. | Read `determining_rules`; `errors` tells "denied by policy" from "could not evaluate". See [Tokens and grants](../guides/tokens-and-grants.md). | | `RESOURCE_NOT_FOUND` | 404 | The addressed row, namespace or document does not exist, or is not visible to the caller. | Check the identity tuple and key. Ops addressed only by an org-wide id answer as for a missing row (`found: false`, `updated: false`, `redacted: false`, `removed: false`) when the caller lacks the op's role on the row's namespace, rather than 404, so they never confirm it exists ([row-scoped operations](../architecture/security.md#row-scoped-operations)). | -| `PRECONDITION_FAILED` | 409 | `if_match_sha256` does not match the live row: another writer changed it. Under the Postgres authority, also an erasure that removed some of a snapshot's memories from the namespace while a `namespace.restore` of it ran. | `detail.current_sha256` is the live hash. Re-read if your change depends on the new value, then resend with that hash; no separate read is needed to retry a blind overwrite. For the restore (no hash), retry it: it leaves out the erased memories. | +| `PRECONDITION_FAILED` | 409 | `if_match_sha256` does not match the live row: another writer changed it. Under the Postgres authority, also an erasure that removed some of a snapshot's memories from the namespace while a `namespace.restore` of it ran. | `detail.current_sha256` is the live hash. Re-read if your change depends on the new value, then resend with that hash; no separate read is needed to retry a blind overwrite. For `memory.verify`, read the row again and attest what it says: resending the returned hash attests content nobody read. For the restore (no hash), retry it: it leaves out the erased memories. | | `WRONG_CELL` | 409 | The org the call acts in is placed in another [cell](../architecture/cells.md) of this deployment, or in none and the caller is not scoped to it; nothing was written. | Call the org's cell: `detail.cell` names it when this cell knows where the org is placed ('' otherwise), and `GET /cells/lookup?org=` on the router gives its cell and host; a new org reaches a cell through a request with a token of that org. | | `PINNED_CONFLICT` | 409 | `memory.set` on a key, or close to a fact, that is pinned. A write that does not pin never replaces a pinned memory. `detail.pinned_blocker_id` names the blocking row. | Change it with `memory.update` (keeps the pin) or `memory.pin` (re-pins), or store the new fact under its own key. | | `IDEMPOTENT_CONFLICT` | 409 | An `Idempotency-Key` (or MCP `_idempotency_key`) reused with a different body for the same op and caller. | Use a new key per distinct request. Resending the original body with the old key replays the stored answer. | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index afcfd662669..0b323b07c46 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -563,7 +563,7 @@ Fields for every `memory` op: [operations/memory.md](operations/memory.md). | [`memory.unpin`](operations/memory.md#memoryunpin) | Remove the write-time pin from one live memory. | admin | idempotent | no | yes | | [`memory.update`](operations/memory.md#memoryupdate) | Key-addressed update: the fact changed or got more specific. | writer | write | yes | | | [`memory.update_by_id`](operations/memory.md#memoryupdate_by_id) | Update a memory by UUID with an optimistic concurrency check. | writer | idempotent | yes | | -| [`memory.verify`](operations/memory.md#memoryverify) | Attest or revoke, refusing a changed source with retryable 503 `ADMISSION_CONTENDED` without writing a memory version; review the current row before retrying. | writer | idempotent | yes | yes | +| [`memory.verify`](operations/memory.md#memoryverify) | Attest or revoke, refusing content other than `if_match_sha256` with 409 `PRECONDITION_FAILED` and a source that changes during the call with retryable 503 `ADMISSION_CONTENDED`. | writer | idempotent | yes | yes | ### memory_schema diff --git a/docs/reference/operations/memory.md b/docs/reference/operations/memory.md index df4d232941a..58b136caefa 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -2491,7 +2491,7 @@ Update a memory by UUID with an optimistic concurrency check. ## `memory.verify` -Attest or revoke, refusing a changed source with retryable 503 `ADMISSION_CONTENDED` without writing a memory version; review the current row before retrying. +Attest or revoke, refusing content other than `if_match_sha256` with 409 `PRECONDITION_FAILED` and a source that changes during the call with retryable 503 `ADMISSION_CONTENDED`. `POST /v1/memory.verify` · MCP `loom_memory_verify` · role `writer` · idempotent · audited @@ -2505,6 +2505,7 @@ Attest or revoke, refusing a changed source with retryable 503 `ADMISSION_CONTEN | `session_id` | `str` | `'-'` | The session or conversation the row belongs to; `'-'` for none. | | `memory_key` | `str` | `''` | With `namespace` and the writer identity, the row to attest when no `memory_id` is sent. | | `revoke` | `bool` | `False` | True clears the attestation instead of making one. | +| `if_match_sha256` | `str` | `''` | The `content_sha256` of the read being attested or revoked: another live hash answers 409 `PRECONDITION_FAILED` and writes nothing; '' checks nothing. | | `actor` | `str` | `''` | Attester recorded when the server runs without auth (`human:` / `process:` + subject); under auth the token decides. | | Output field | Type | Meaning | diff --git a/frontend/src/api.memory.test.ts b/frontend/src/api.memory.test.ts index 2bdfd428d75..77ed2d83fb9 100644 --- a/frontend/src/api.memory.test.ts +++ b/frontend/src/api.memory.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it, vi } from "vitest"; -import { getMemoryById, type MemoryDetail, pinMemory, unpinMemory } from "./api"; +import { getMemoryById, type MemoryDetail, pinMemory, rowIdentity, unpinMemory, verifyMemory } from "./api"; afterEach(() => vi.unstubAllGlobals()); @@ -121,6 +121,65 @@ describe("pinMemory", () => { }); }); +describe("verifyMemory", () => { + const row: MemoryDetail = { + found: true, + value: "deploys freeze on Fridays", + memory_type: "semantic", + confidence: 1, + version: 3, + pinned: false, + created_at: "2026-09-18T09:00:00Z", + agent: "support-bot", + user_id: "alice", + session_id: "s1", + content_sha256: "abc", + }; + + async function verifyBody(detail: MemoryDetail, revoke = false): Promise> { + vi.stubGlobal("localStorage", { + getItem: vi.fn(() => null), + setItem: vi.fn(), + removeItem: vi.fn(), + clear: vi.fn(), + key: vi.fn(() => null), + length: 0, + }); + const fetchMock = vi.fn( + async (..._args: Parameters): Promise => + new Response(JSON.stringify({ found: true, changed: true }), { status: 200 }), + ); + vi.stubGlobal("fetch", fetchMock); + const id = rowIdentity({ org: "dev", namespace: "local", agent: "loom-ui" }, detail); + await verifyMemory(id, "deploy/freeze", { revoke, ifMatchSha256: detail.content_sha256 }); + const [url, init] = fetchMock.mock.calls[0]!; + expect(url).toBe("/v1/memory.verify"); + return JSON.parse(String(init?.body)); + } + + // The hash names one row's content: the call addresses that row, not the caller's own. + it("sends the hash of the content shown, at the row's own agent, user and session", async () => { + expect(await verifyBody(row)).toEqual({ + consumer: "loom-ui", + org: "dev", + namespace: "local", + agent: "support-bot", + user_id: "alice", + session_id: "s1", + memory_key: "deploy/freeze", + revoke: false, + if_match_sha256: "abc", + }); + expect(await verifyBody(row, true)).toMatchObject({ revoke: true, if_match_sha256: "abc" }); + }); + + it("sends no precondition when the read carried no hash", async () => { + const body = await verifyBody({ ...row, user_id: undefined, session_id: undefined, content_sha256: undefined }); + expect(body).not.toHaveProperty("if_match_sha256"); + expect(body).toMatchObject({ agent: "support-bot", user_id: "-", session_id: "-" }); + }); +}); + describe("getMemoryById", () => { it("asks for a high row without its value when the caller only names it", async () => { vi.stubGlobal("localStorage", { diff --git a/frontend/src/api.ts b/frontend/src/api.ts index a9c4ad72c02..3535f057f9a 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -789,20 +789,20 @@ export interface VerifyResult { /** Attest to one memory as the signed-in person, or revoke the attestation. * The server derives the actor from the token (`human:`), so the - * UI never chooses it. Binds to the row's current content. */ + * UI never chooses it. `id` may name the row's agent, user and session + * (`rowIdentity`); user and session default to '-'. `ifMatchSha256` is the hash of + * the content the page shows: a row that holds other content answers 409. */ export async function verifyMemory( id: Identity, key: string, - opts: { revoke?: boolean; userId?: string; sessionId?: string } = {}, + opts: { revoke?: boolean; ifMatchSha256?: string } = {}, ): Promise { return post("/v1/memory.verify", { - org: id.org, - namespace: id.namespace, - agent: id.agent, - user_id: opts.userId || "-", - session_id: opts.sessionId || "-", + ...id, memory_key: key, revoke: !!opts.revoke, + // An undefined field is left out of the body: no hash, no precondition. + if_match_sha256: opts.ifMatchSha256 || undefined, }); } diff --git a/frontend/src/components/MemoryInspector.lifecycle.test.tsx b/frontend/src/components/MemoryInspector.lifecycle.test.tsx index a21cadbfb80..32a4b66e201 100644 --- a/frontend/src/components/MemoryInspector.lifecycle.test.tsx +++ b/frontend/src/components/MemoryInspector.lifecycle.test.tsx @@ -2,6 +2,7 @@ import { act, cleanup, render, screen, waitFor, within } from "../test/rtl"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { MemoryDetail, MyNamespaceEntry, WhoAmI } from "../api"; +import { ApiError } from "../lib/errors"; import { useStore } from "../lib/state"; import { resetNamespaceRoleCache } from "../lib/namespaceRole"; import { axeViolations } from "../test/axe"; @@ -351,6 +352,59 @@ describe("MemoryInspector lifecycle actions", () => { await waitFor(() => expect(toast).toHaveBeenCalledWith("This memory carried no lock", "info")); }); + // The attestation is of what the drawer shows: the call names that row and its hash. + it("verifies the row it shows with the hash of the value it shows", async () => { + const attested = { + found: true, + changed: true, + verified_by: "human:o@example.com", + verified_at: "2026-09-18T10:00:00Z", + verification: "human" as const, + content_sha256: "abc", + }; + vi.mocked(api.verifyMemory).mockResolvedValue(attested); + await open("writer", { ...LIVE, content_sha256: "abc" }); + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); + await waitFor(() => + expect(api.verifyMemory).toHaveBeenCalledWith(row, "coffee_pref", { revoke: false, ifMatchSha256: "abc" }), + ); + await waitFor(() => expect(toast).toHaveBeenCalledWith("Verified as human:o@example.com", "ok")); + + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Remove verification" })); + await waitFor(() => + expect(api.verifyMemory).toHaveBeenLastCalledWith(row, "coffee_pref", { revoke: true, ifMatchSha256: "abc" }), + ); + }); + + it("reads the memory again when a verify is refused because the content changed", async () => { + vi.mocked(api.verifyMemory).mockRejectedValueOnce( + new ApiError({ status: 409, code: "PRECONDITION_FAILED", detail: { current_sha256: "def" } }), + ); + await open("writer", { ...LIVE, content_sha256: "abc" }); + vi.mocked(api.getMemory).mockResolvedValue({ ...LIVE, value: "oat milk, one sugar", content_sha256: "def" }); + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); + await waitFor(() => + expect(toast).toHaveBeenCalledWith( + "This memory changed since it was opened. Check the current content, then try again.", + "info", + ), + ); + expect(await screen.findByText("oat milk, one sugar")).toBeInTheDocument(); + expect(toastError).not.toHaveBeenCalled(); + // The next try attests the text now shown, never the hash the refusal returned unread. + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); + await waitFor(() => + expect(api.verifyMemory).toHaveBeenLastCalledWith(row, "coffee_pref", { revoke: false, ifMatchSha256: "def" }), + ); + cleanup(); + + const down = new ApiError({ status: 503, code: "ADMISSION_CONTENDED" }); + vi.mocked(api.verifyMemory).mockRejectedValueOnce(down); + await open("writer", { ...LIVE, content_sha256: "abc" }); + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); + await waitFor(() => expect(toastError).toHaveBeenCalledWith("Verify failed", down)); + }); + it("says why a share was refused", async () => { vi.mocked(lc.shareMemory).mockRejectedValueOnce(new Error("a shared memory already holds this key")); await open("admin"); diff --git a/frontend/src/components/MemoryInspector.tsx b/frontend/src/components/MemoryInspector.tsx index 90e06e9021c..3ac20a7c92a 100644 --- a/frontend/src/components/MemoryInspector.tsx +++ b/frontend/src/components/MemoryInspector.tsx @@ -54,7 +54,7 @@ import { LockMemoryDialog, RedactVersionDialog, RejectMemoryDialog } from "../fl import { navigationHref, useStore } from "../lib/state"; import { openerUsable } from "../lib/place"; import { graphSeedHref, isModifiedClick, openGraphAt } from "../lib/graphLink"; -import { isPublicationPending } from "../lib/errors"; +import { ApiError, isPublicationPending } from "../lib/errors"; import { AgentBadge } from "./AgentBadge"; import { DiffView } from "./DiffView"; import { keepOpenOnToasts, toast, toastError } from "./Toast"; @@ -571,15 +571,22 @@ export function MemoryInspector({ if (!detail || verifyReason) return; const live = detail.verification === "human" || detail.verification === "process"; try { - const r = await verifyMemory(identity, memoryKey, { + // At the row's own identity: the hash is that row's, and the drawer's agent may + // name another row or none. + const r = await verifyMemory(rowIdentity(identity, detail), memoryKey, { revoke: live, - userId: detail.user_id || undefined, - sessionId: detail.session_id || undefined, + ifMatchSha256: detail.content_sha256, }); setDetail({ ...detail, verified_by: r.verified_by, verified_at: r.verified_at, verification: r.verification }); toast(live ? "Verification removed" : `Verified as ${r.verified_by}`, "ok"); onChanged(); } catch (e) { + if (e instanceof ApiError && e.status === 409 && e.code === "PRECONDITION_FAILED") { + // The row holds other content than the drawer shows: show what it holds. + toast("This memory changed since it was opened. Check the current content, then try again.", "info"); + await reread(); + return; + } toastError("Verify failed", e); } }; diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 6868f00309f..1119f4269a9 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: 89731d59fda7a96ab4476c4e23f20a5d4cb501cc1de5a67c5960b8ad4bbadc43 +// Registry model schema SHA-256: 3397fc37a24a953f57e3300a3143528f6dff612632f88ae2c92d675f42ced5f4 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -9155,15 +9155,16 @@ type MemoryUpdateOutput struct { // MemoryVerifyInput is the request to memory.verify. type MemoryVerifyInput struct { - Org string `json:"org"` - MemoryID *string `json:"memory_id,omitempty"` - Namespace *string `json:"namespace,omitempty"` - Agent *string `json:"agent,omitempty"` - UserID *string `json:"user_id,omitempty"` - SessionID *string `json:"session_id,omitempty"` - MemoryKey *string `json:"memory_key,omitempty"` - Revoke *bool `json:"revoke,omitempty"` - Actor *string `json:"actor,omitempty"` + Org string `json:"org"` + MemoryID *string `json:"memory_id,omitempty"` + Namespace *string `json:"namespace,omitempty"` + Agent *string `json:"agent,omitempty"` + UserID *string `json:"user_id,omitempty"` + SessionID *string `json:"session_id,omitempty"` + MemoryKey *string `json:"memory_key,omitempty"` + Revoke *bool `json:"revoke,omitempty"` + IfMatchSHA256 *string `json:"if_match_sha256,omitempty"` + Actor *string `json:"actor,omitempty"` } // MemoryVerifyOutput is the response from memory.verify. diff --git a/sdk/python/loom/memory.py b/sdk/python/loom/memory.py index fcf6145ed0d..783316cbb85 100644 --- a/sdk/python/loom/memory.py +++ b/sdk/python/loom/memory.py @@ -1112,6 +1112,7 @@ async def verify( actor: str | None = None, user_id: str | None = None, session_id: str | None = None, + if_match_sha256: str | None = None, ) -> dict[str, Any]: """Attest to one memory as the calling identity (or revoke). @@ -1122,6 +1123,9 @@ async def verify( by a dev-mode server with no auth context. Address by `memory_key` (with this Agent's identity) or `memory_id`. + Pass `if_match_sha256`, the `content_sha256` of the read being attested + or revoked, and the server raises `PreconditionFailed` (409) when the row + holds other content. Returns the server's `MemoryVerifyOutput` dict: `found`, `changed`, `verified_by`, `verified_at`, `verification` (human | process | stale | none), `content_sha256`. @@ -1136,6 +1140,8 @@ async def verify( payload["memory_key"] = memory_key if actor: payload["actor"] = actor + if if_match_sha256: + payload["if_match_sha256"] = if_match_sha256 return await self._agent.transport.post("/v1/memory.verify", payload) async def touch( diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 8b0c6c6e7ac..f78c58ac9bf 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -17281,7 +17281,7 @@ class MemoryUpdateByIdOutput(TypedDict, total=False): class MemoryVerifyInput(TypedDict, total=False): - "Attest or revoke, refusing a changed source with retryable 503" + "Attest or revoke, refusing content other than `if_match_sha256` with 409" org: Required[str] memory_id: NotRequired[str] @@ -17291,11 +17291,12 @@ class MemoryVerifyInput(TypedDict, total=False): session_id: NotRequired[str] memory_key: NotRequired[str] revoke: NotRequired[bool] + if_match_sha256: NotRequired[str] actor: NotRequired[str] class MemoryVerifyBody(TypedDict, total=False): - "Attest or revoke, refusing a changed source with retryable 503" + "Attest or revoke, refusing content other than `if_match_sha256` with 409" org: NotRequired[str] memory_id: NotRequired[str] @@ -17305,6 +17306,7 @@ class MemoryVerifyBody(TypedDict, total=False): session_id: NotRequired[str] memory_key: NotRequired[str] revoke: NotRequired[bool] + if_match_sha256: NotRequired[str] actor: NotRequired[str] diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 08e7c12d35d..eedeb00194e 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -271,7 +271,7 @@ module Generated "memory.unpin" => OpSpec.new("memory.unpin", "memory", "unpin", true, false, "admin", "experimental", %w[org namespace agent user_id session_id run_id memory_key].freeze, %w[org namespace agent memory_key].freeze), "memory.update" => OpSpec.new("memory.update", "memory", "update", false, false, "writer", "stable", %w[org namespace memory_key value agent user_id session_id run_id tags concepts confidence reason if_match_sha256 char_limit revive relations].freeze, %w[org namespace memory_key].freeze), "memory.update_by_id" => OpSpec.new("memory.update_by_id", "memory", "update_by_id", true, false, "writer", "stable", %w[org memory_id value tags concepts if_match_sha256 char_limit revive relations].freeze, %w[org memory_id].freeze), - "memory.verify" => OpSpec.new("memory.verify", "memory", "verify", true, false, "writer", "stable", %w[org memory_id namespace agent user_id session_id memory_key revoke actor].freeze, %w[org].freeze), + "memory.verify" => OpSpec.new("memory.verify", "memory", "verify", true, false, "writer", "stable", %w[org memory_id namespace agent user_id session_id memory_key revoke if_match_sha256 actor].freeze, %w[org].freeze), "memory_schema.approve" => OpSpec.new("memory_schema.approve", "memory_schema", "approve", false, false, "admin", "experimental", %w[org namespace name decision reviewed_by].freeze, %w[org namespace name decision].freeze), "memory_schema.list" => OpSpec.new("memory_schema.list", "memory_schema", "list", true, true, "viewer", "experimental", %w[org namespace include_proposed limit].freeze, %w[org namespace].freeze), "memory_schema.propose" => OpSpec.new("memory_schema.propose", "memory_schema", "propose", false, false, "writer", "experimental", %w[org namespace name description fields created_by status].freeze, %w[org namespace name fields].freeze), @@ -2168,7 +2168,7 @@ def update_by_id(body = nil, request_options: nil, **fields) end # `memory.verify` (writer, writes, Idempotency-Key). - # Attest or revoke, refusing a changed source with retryable 503 + # Attest or revoke, refusing content other than `if_match_sha256` with 409 # Required: org. def verify(body = nil, request_options: nil, **fields) call_op("memory.verify", body, fields, request_options) diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index bbe9ff73ebe..90f1421398e 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -44794,6 +44794,12 @@ pub struct MemoryVerifyInput { skip_serializing_if = "Option::is_none", deserialize_with = "present_value" )] + pub if_match_sha256: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] pub actor: Option, } impl Default for MemoryVerifyInput { @@ -44812,6 +44818,7 @@ impl MemoryVerifyInput { session_id: None, memory_key: None, revoke: None, + if_match_sha256: None, actor: None, } } @@ -44847,6 +44854,10 @@ impl MemoryVerifyInput { self.revoke = Some(revoke); self } + pub fn if_match_sha256(mut self, if_match_sha256: impl Into) -> Self { + self.if_match_sha256 = Some(if_match_sha256.into()); + self + } pub fn actor(mut self, actor: impl Into) -> Self { self.actor = Some(actor.into()); self diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 2a902220d20..ab4172eb8db 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -8051,6 +8051,7 @@ export interface MemoryVerifyInput { session_id?: string; memory_key?: string; revoke?: boolean; + if_match_sha256?: string; actor?: string; } diff --git a/server/memory/api/models_crud.py b/server/memory/api/models_crud.py index 8b30d9eb7be..9db82630e4a 100644 --- a/server/memory/api/models_crud.py +++ b/server/memory/api/models_crud.py @@ -1283,8 +1283,9 @@ class MemorySweepExpiredOutput(BaseModel): class MemoryVerifyInput(BaseModel): - """Attest or revoke, refusing a changed source with retryable 503 - `ADMISSION_CONTENDED` without writing a memory version; review the current row + """Attest or revoke, refusing content other than `if_match_sha256` with 409 + `PRECONDITION_FAILED` and a source that changes during the call with retryable 503 + `ADMISSION_CONTENDED`. A refusal writes no memory version; read the current row before retrying. Address the row by `memory_id`, or by `namespace` + `memory_key` with the @@ -1309,6 +1310,9 @@ class MemoryVerifyInput(BaseModel): memory_key: str = "" # True clears the attestation instead of making one. revoke: bool = False + # The `content_sha256` of the read being attested or revoked: another live hash + # answers 409 `PRECONDITION_FAILED` and writes nothing; '' checks nothing. + if_match_sha256: str = "" # Attester recorded when the server runs without auth (`human:` / `process:` + # subject); under auth the token decides. actor: str = "" diff --git a/server/memory/app/verify.py b/server/memory/app/verify.py index 021e2977f03..d31b8e50690 100644 --- a/server/memory/app/verify.py +++ b/server/memory/app/verify.py @@ -15,6 +15,8 @@ checked before the lookup; by memory_id, the namespace holding the id is the one the caller can write (`id_namespace.namespace_for_id`), and a row it cannot reach reads as not found. + * `if_match_sha256` names the content the caller read: another live hash + answers 409 before anything is written, for an attestation and a revoke alike. * A new ReplacingMergeTree version row is written through `build_memory_version_row`, carrying every column forward; the three attestation columns and `content_sha256` are the only deltas. The @@ -36,6 +38,7 @@ from server.auth.context import current_auth from server.core.ch import get_client from server.core.datetimes import naive_utc_now +from server.core.errors import PreconditionFailedError from server.core.hashing import served_content_sha256 from server.identity.domain.read_scope import WHOLE_NAMESPACE from server.memory.api.models_crud import MemoryVerifyInput, MemoryVerifyOutput @@ -142,6 +145,14 @@ async def handle_memory_verify(input: MemoryVerifyInput) -> MemoryVerifyOutput: return MemoryVerifyOutput(found=False) sha = current_content_sha256(row) + if input.if_match_sha256 and input.if_match_sha256 != sha: + # The caller read other content than the row holds: an attestation or a revoke + # would record a verdict on text the caller did not see. + raise PreconditionFailedError( + "the memory holds other content than if_match_sha256 names; " + "read it again before attesting or revoking", + current_sha256=sha, + ) before = trust.verification_state(row.verified_by, row.verified_sha256, sha) if input.revoke: diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index aa39ac5db50..e3e91b28f25 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -502,7 +502,10 @@ def revision_policy(update: str) -> str: "Attest that a memory is TRUE, as the signed-in person (or revoke " "that attestation). Use only when the user explicitly confirms a " "fact ('yes, that's right', 'mark that as verified') — never on your " - "own judgement. The attestation binds to the memory's content: a " + "own judgement. Send if_match_sha256, the content_sha256 of the read " + "the user confirmed; a 409 means the memory changed: show the current " + "text and ask again, never resend the returned hash unseen. " + "The attestation binds to the memory's content: a " "later edit shows it as `stale` until re-verified. Address by " "memory_id, or namespace + memory_key. Returns verification state " "human | process | stale | none." diff --git a/tests/integration/test_memory_verify.py b/tests/integration/test_memory_verify.py index d873350fdfa..0484964c6d4 100644 --- a/tests/integration/test_memory_verify.py +++ b/tests/integration/test_memory_verify.py @@ -188,3 +188,39 @@ async def test_a_set_or_bulk_set_revision_keeps_the_attestation_as_stale( got = await a.memory.get(key) assert got["verification"] == "stale", key assert got["verified_by"] == "human:alice", key + + +@pytest.mark.asyncio +async def test_verify_refuses_the_hash_of_an_edited_row(control_plane_url) -> None: + """`if_match_sha256` names the content the caller read: after an edit that hash + attests nothing and revokes nothing, and the row keeps the state it had.""" + from loom import Agent, PreconditionFailed + + ns = f"vf-{uuid.uuid4().hex[:6]}" + tok = _human_token(org=ORG, namespaces=[ns], subject="alice") + async with Agent( + org=ORG, namespace=ns, agent="t", base_url=control_plane_url, api_key=tok + ) as a: + w = await a.memory.set("on_call", "Rota A covers weekends.", memory_type="semantic") + read = w["content_sha256"] + upd = await a.memory.update_by_id(w["memory_id"], "Rota B covers weekends.") + live = upd["content_sha256"] + assert upd["updated"] and live != read + + with pytest.raises(PreconditionFailed) as refused: + await a.memory.verify("on_call", if_match_sha256=read) + assert refused.value.current_sha256 == live + got = await a.memory.get("on_call") + assert got["verification"] == "none" and got["verified_by"] == "" + assert got["content_sha256"] == live and got["version"] == upd["new_version"] + + v = await a.memory.verify(memory_id=w["memory_id"], if_match_sha256=live) + assert v["found"] and v["changed"] and v["verification"] == "human" + assert v["verified_by"] == "human:alice" and v["content_sha256"] == live + + with pytest.raises(PreconditionFailed) as refused: + await a.memory.verify("on_call", revoke=True, if_match_sha256=read) + assert refused.value.current_sha256 == live + got = await a.memory.get("on_call") + assert got["verification"] == "human" and got["verified_by"] == "human:alice" + assert got["content_sha256"] == live and got["version"] == v["version"] diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 5ff93acde62..9194b99310d 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -426,7 +426,7 @@ "sdk/python/loom/integrations/langgraph.py": "5d68e6ab1645d868477a13b14aa6d734c72f72057464cac9a21aa707add17e7b", "sdk/python/loom/integrations/llamaindex.py": "06eaa071115cad752d27bdc9bf7c4d5b6f5d7d39d9896267fcd459a4e06bf661", "sdk/python/loom/integrations/openai_agents.py": "143fe1df060b96550a33f77fa44416e291c2154552e433f8309275f61c8fca2a", - "sdk/python/loom/memory.py": "950106559dd036b3eddb0a47cc931fba6e033abe15f93fd98323452d26170f48", + "sdk/python/loom/memory.py": "46ead264f3287a801f39c784f832909599806a8abbd84cb766100dec80110c35", "sdk/python/loom/run.py": "e8a226167889f9657f93ffa9b00b46cdda70de49ce236c07da1124a2f23b3832", "sdk/python/loom/session.py": "5f0fd61fcfdbf9d60888b111887fca8f32e24eb51ca9ff04a256901657c3202b", "sdk/typescript/src/integrations/claude-memory.ts": "c846f0011d7cf1ba4b30e99fbfd8adb6b29abff56856d0dbe14fba620007f6bc", diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index 23492cbfac7..b53ddde7e4a 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -3296,7 +3296,8 @@ "revoke", "actor", "user_id", - "session_id" + "session_id", + "if_match_sha256" ] }, "nested": { diff --git a/tests/unit/test_memory_verify.py b/tests/unit/test_memory_verify.py index ef13ff4bf10..1699dd32cfc 100644 --- a/tests/unit/test_memory_verify.py +++ b/tests/unit/test_memory_verify.py @@ -18,6 +18,7 @@ from server.auth import authz from server.auth.context import set_current_auth from server.auth.jwt import AuthInfo +from server.core.errors import PreconditionFailedError from server.core.hashing import sha256_value_json from server.memory.api.models_crud import MemoryVerifyInput, MemoryVerifyOutput from server.memory.app import after_write @@ -353,6 +354,123 @@ async def test_revoke_clears_and_is_idempotent(monkeypatch: pytest.MonkeyPatch) assert out.found and out.changed is False and ch.inserted == [] +# ---------------- the hash the caller read ---------------- + + +def _record_mirrors(monkeypatch: pytest.MonkeyPatch) -> list[tuple[Any, ...]]: + """Record each scheduled embeddings mirror in place of running it.""" + scheduled: list[tuple[Any, ...]] = [] + + def record(*args: Any, **kw: Any) -> None: + scheduled.append(args) + + monkeypatch.setattr(mv, "_schedule_mirror", record) + return scheduled + + +@pytest.mark.asyncio +async def test_another_hash_than_the_live_one_is_refused_and_writes_nothing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + row = _row() + ch = _wire(monkeypatch, row) + scheduled = _record_mirrors(monkeypatch) + set_current_auth(_token("alice")) + live = mv.current_content_sha256(row) + + with pytest.raises(PreconditionFailedError) as ei: + await mv.handle_memory_verify( + MemoryVerifyInput( + org="o", memory_id=row.memory_id, if_match_sha256=_sha("what alice read") + ) + ) + + assert ei.value.extra["current_sha256"] == live + assert live not in ei.value.message + assert ch.inserted == [] and scheduled == [] + + +@pytest.mark.asyncio +async def test_the_live_hash_attests(monkeypatch: pytest.MonkeyPatch) -> None: + row = _row() + ch = _wire(monkeypatch, row) + scheduled = _record_mirrors(monkeypatch) + set_current_auth(_token("alice")) + + out = await mv.handle_memory_verify( + MemoryVerifyInput( + org="o", memory_id=row.memory_id, if_match_sha256=mv.current_content_sha256(row) + ) + ) + + assert out.changed and out.verification == "human" + ((table, rows),) = ch.inserted + assert table == "loom.memory" and len(rows) == 1 + assert len(scheduled) == 1 + + +@pytest.mark.asyncio +async def test_a_repeat_verify_still_checks_the_hash(monkeypatch: pytest.MonkeyPatch) -> None: + """Without the check a repeat verify by the same actor answers `changed=False`.""" + sha = _sha("Tue and Thu only; never Friday.") + attested = _row(verified_by="human:alice", verified_sha256=sha, verified_at=_NOW) + ch = _wire(monkeypatch, attested) + set_current_auth(_token("alice")) + + with pytest.raises(PreconditionFailedError) as ei: + await mv.handle_memory_verify( + MemoryVerifyInput( + org="o", memory_id=attested.memory_id, if_match_sha256=_sha("an earlier text") + ) + ) + + assert ei.value.extra["current_sha256"] == sha and ch.inserted == [] + + +@pytest.mark.asyncio +async def test_a_revoke_checks_the_hash_when_sent(monkeypatch: pytest.MonkeyPatch) -> None: + sha = _sha("Tue and Thu only; never Friday.") + attested = _row(verified_by="human:alice", verified_sha256=sha, verified_at=_NOW) + ch = _wire(monkeypatch, attested) + scheduled = _record_mirrors(monkeypatch) + set_current_auth(_token("someone-else")) + + with pytest.raises(PreconditionFailedError): + await mv.handle_memory_verify( + MemoryVerifyInput( + org="o", + memory_id=attested.memory_id, + revoke=True, + if_match_sha256=_sha("an earlier text"), + ) + ) + assert ch.inserted == [] and scheduled == [] + + out = await mv.handle_memory_verify( + MemoryVerifyInput(org="o", memory_id=attested.memory_id, revoke=True, if_match_sha256=sha) + ) + assert out.changed and out.verification == "none" and len(ch.inserted) == 1 + + +@pytest.mark.asyncio +async def test_a_missing_row_answers_not_found_whatever_the_hash( + monkeypatch: pytest.MonkeyPatch, +) -> None: + row = _row() + ch = _wire(monkeypatch, row) + set_current_auth(_token("alice")) + missing = await mv.handle_memory_verify( + MemoryVerifyInput(org="o", memory_id="nope", if_match_sha256=_sha("anything")) + ) + assert missing == MemoryVerifyOutput(found=False) + # A row the caller cannot write reads as missing: no 409 carries its hash. + set_current_auth(_token("intruder", allowed=False)) + foreign = await mv.handle_memory_verify( + MemoryVerifyInput(org="o", memory_id=row.memory_id, if_match_sha256=_sha("anything")) + ) + assert foreign == MemoryVerifyOutput(found=False) and ch.inserted == [] + + # ---------------- surfaces ---------------- @@ -367,6 +485,7 @@ def test_registered_audited_and_callable_by_name_over_mcp() -> None: assert "memory.verify" not in toolsets._MCP_HIDDEN_OPS assert "memory.verify" not in toolsets._MCP_CORE_OPS # a human act, not a chat-loop verb assert "stale" in mcp_descriptions.TOOL_DESCRIPTIONS["memory.verify"] + assert "if_match_sha256" in mcp_descriptions.TOOL_DESCRIPTIONS["memory.verify"] def test_get_outputs_carry_the_derived_state() -> None: diff --git a/tests/unit/test_sdk_write_kwargs.py b/tests/unit/test_sdk_write_kwargs.py index 498a0bf3c19..a3b92ffbcaf 100644 --- a/tests/unit/test_sdk_write_kwargs.py +++ b/tests/unit/test_sdk_write_kwargs.py @@ -145,3 +145,13 @@ async def test_set_from_messages_sends_defer_only_when_given(agent: Agent) -> No assert t.last("/v1/memory.set_from_messages")["defer"] is False await agent.memory.set_from_messages(turns, defer=True) assert t.last("/v1/memory.set_from_messages")["defer"] is True + + +async def test_verify_sends_the_hash_it_is_given(agent: Agent) -> None: + t: Any = agent.transport + await agent.memory.verify(memory_id="m1", if_match_sha256="abc") + assert t.last("/v1/memory.verify")["if_match_sha256"] == "abc" + await agent.memory.verify("k", revoke=True, if_match_sha256="abc") + assert t.last("/v1/memory.verify")["if_match_sha256"] == "abc" + await agent.memory.verify(memory_id="m1") + assert "if_match_sha256" not in t.last("/v1/memory.verify") From 4684f6c335c38cde1c240d1efa12a7385f4114e1 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 23:54:16 +0000 Subject: [PATCH 2/5] memory.verify's 409 carries no hash for a high row, and a hash sent as content_sha256 is refused The 409 of `if_match_sha256` returned the live hash of any row. For a `high` row that hash names a short secret as well as the value does, the refusal writes no audit row, and `memory.get` and `memory.get_by_id` serve the hash with a `memory.sensitive_read` row. The refusal of a `high` row carries an empty `current_sha256`, a shape the error already has. Every read serves the hash as `content_sha256`. Sent under that name, `memory.verify` served the call, attested with no precondition and named the key in `ignored_args`: the name heuristic of `arg_check` finds no near field. One entry in `SYNONYMS` reads `content_sha256` as `if_match_sha256`, so a write answers 422 `UNKNOWN_ARGUMENT` and writes nothing. The table is not keyed by op: `memory.set`, `memory.update`, `memory.update_by_id`, `memory.move`, `memory.pin` and `profile.set` take the same field and refuse the same key. The hash to send is the one `memory.get` or `memory.get_by_id` returned. `memory.set`, `memory.list` and `memory.bulk_get` report the hash of the value as it was sent, which is another hash for an object value whose numbers the JSON column renders in another form. The field comment, the feature pages, `MemoryClient.verify` and the MCP description name the two reads; the MCP description also says a search hit carries no hash. The Python SDK told a caller to retry a 409 with `.current_sha256`, which for `memory.verify` attests content nobody read. The `PreconditionFailed` docstring, its row in the Python reference and `MemoryClient.verify` say to read the row again first. The reviewed-sender pin of `sdk/python/loom/memory.py` is renewed for the docstring. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../features/memory/history-and-provenance.md | 9 +++--- docs/features/memory/writing.md | 12 ++++---- docs/reference/errors.md | 2 +- docs/reference/operations/memory.md | 2 +- docs/reference/python-sdk.md | 2 +- sdk/python/loom/errors.py | 7 +++-- sdk/python/loom/memory.py | 8 +++-- server/memory/api/models_crud.py | 5 ++-- server/memory/app/verify.py | 4 ++- server/transport/arg_check.py | 7 +++-- server/transport/mcp_descriptions.py | 5 ++-- tests/unit/session_content_senders.json | 2 +- tests/unit/test_arg_feedback.py | 29 +++++++++++++++++++ tests/unit/test_memory_verify.py | 19 ++++++++++++ 14 files changed, 86 insertions(+), 27 deletions(-) diff --git a/docs/features/memory/history-and-provenance.md b/docs/features/memory/history-and-provenance.md index 16044144433..b06fc4b77fe 100644 --- a/docs/features/memory/history-and-provenance.md +++ b/docs/features/memory/history-and-provenance.md @@ -120,10 +120,11 @@ actor from the caller's token and the content hash they attested. Address the ro `memory_id`, or by `namespace` and `memory_key` with the writer identity. It needs writer on the row's namespace. -Send `if_match_sha256`, the `content_sha256` of the read being attested, and the call -attests only that content. A row that holds other content answers 409 -`PRECONDITION_FAILED` with `current_sha256` and writes nothing: read the row again and -attest what it says, never the returned hash unread. `revoke=true` takes the same +Send `if_match_sha256`, the `content_sha256` that `memory.get` or `memory.get_by_id` +returned for the content being attested, and the call attests only that content. A row +that holds other content answers 409 `PRECONDITION_FAILED` with `current_sha256` and +writes nothing: read the row again and attest what it says, never the returned hash +unread. The 409 of a `high` row carries no hash. `revoke=true` takes the same precondition. Without the field the call attests the row as the server reads it, so an edit that lands after the caller's read is attested unseen. diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index 2216ecf7613..38fd183fc0f 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -145,11 +145,13 @@ async with Agent(org="acme", namespace="support", agent="triage-bot") as agent: ... # re-read (the error carries current_sha256), decide, retry ``` -`memory.update`, `memory.update_by_id`, `memory.move` (source row) and -[`memory.verify`](./history-and-provenance.md#attestation-memoryverify) (the row being -attested or revoked) accept the same precondition. The Python SDK coalesces a burst of -`set` calls from one identity into one -`memory.bulk_set` (from the third set inside 200 ms); a coalesced result carries +`memory.update`, `memory.update_by_id` and `memory.move` (source row) accept the same +precondition. [`memory.verify`](./history-and-provenance.md#attestation-memoryverify) +accepts it for the row being attested or revoked, and takes the hash a `memory.get` or +`memory.get_by_id` read returned. A write that carries the hash as `content_sha256`, the +name a read serves it under, is refused with 422 `UNKNOWN_ARGUMENT`, which names +`if_match_sha256`. The Python SDK coalesces a burst of `set` calls from one identity +into one `memory.bulk_set` (from the third set inside 200 ms); a coalesced result carries `coalesced: true` and no `content_sha256`. A set with `if_match_sha256` is never coalesced. diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 2e67dd73393..22552515d25 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -172,7 +172,7 @@ resend are in each page's Errors section. Each op's kind is in the | `AUTH_INSUFFICIENT` | 403 | The token's role or namespace access does not cover the op (over MCP the result carries `required_role`). The assistant's refusals carry `reason`: `org_wide`, `narrowed` or `token_expires_soon` with `left_s` ([the assistant's refusals](../architecture/assistant.md#each-callers-own-identity)). | A namespace that does not exist is refused with the same code as one the token may not read, so check the name against `namespace.list_mine` first. Then compare the op's role in the [operations reference](./operations.md) with the token (`GET /v1/whoami`) and ask a namespace admin for a grant. | | `POLICY_FORBIDDEN` | 403 | A history-policy rule denied the call (`decision`, `determining_rules`, `errors`) with `LOOM_POLICY_MODE=enforce`. | Read `determining_rules`; `errors` tells "denied by policy" from "could not evaluate". See [Tokens and grants](../guides/tokens-and-grants.md). | | `RESOURCE_NOT_FOUND` | 404 | The addressed row, namespace or document does not exist, or is not visible to the caller. | Check the identity tuple and key. Ops addressed only by an org-wide id answer as for a missing row (`found: false`, `updated: false`, `redacted: false`, `removed: false`) when the caller lacks the op's role on the row's namespace, rather than 404, so they never confirm it exists ([row-scoped operations](../architecture/security.md#row-scoped-operations)). | -| `PRECONDITION_FAILED` | 409 | `if_match_sha256` does not match the live row: another writer changed it. Under the Postgres authority, also an erasure that removed some of a snapshot's memories from the namespace while a `namespace.restore` of it ran. | `detail.current_sha256` is the live hash. Re-read if your change depends on the new value, then resend with that hash; no separate read is needed to retry a blind overwrite. For `memory.verify`, read the row again and attest what it says: resending the returned hash attests content nobody read. For the restore (no hash), retry it: it leaves out the erased memories. | +| `PRECONDITION_FAILED` | 409 | `if_match_sha256` does not match the live row: another writer changed it. Under the Postgres authority, also an erasure that removed some of a snapshot's memories from the namespace while a `namespace.restore` of it ran. | `detail.current_sha256` is the live hash. Re-read if your change depends on the new value, then resend with that hash; no separate read is needed to retry a blind overwrite. For `memory.verify`, read the row again and attest what it says: resending the returned hash attests content nobody read, and the 409 of a `high` row carries none. For the restore (no hash), retry it: it leaves out the erased memories. | | `WRONG_CELL` | 409 | The org the call acts in is placed in another [cell](../architecture/cells.md) of this deployment, or in none and the caller is not scoped to it; nothing was written. | Call the org's cell: `detail.cell` names it when this cell knows where the org is placed ('' otherwise), and `GET /cells/lookup?org=` on the router gives its cell and host; a new org reaches a cell through a request with a token of that org. | | `PINNED_CONFLICT` | 409 | `memory.set` on a key, or close to a fact, that is pinned. A write that does not pin never replaces a pinned memory. `detail.pinned_blocker_id` names the blocking row. | Change it with `memory.update` (keeps the pin) or `memory.pin` (re-pins), or store the new fact under its own key. | | `IDEMPOTENT_CONFLICT` | 409 | An `Idempotency-Key` (or MCP `_idempotency_key`) reused with a different body for the same op and caller. | Use a new key per distinct request. Resending the original body with the old key replays the stored answer. | diff --git a/docs/reference/operations/memory.md b/docs/reference/operations/memory.md index 58b136caefa..e075f6d4439 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -2505,7 +2505,7 @@ Attest or revoke, refusing content other than `if_match_sha256` with 409 `PRECON | `session_id` | `str` | `'-'` | The session or conversation the row belongs to; `'-'` for none. | | `memory_key` | `str` | `''` | With `namespace` and the writer identity, the row to attest when no `memory_id` is sent. | | `revoke` | `bool` | `False` | True clears the attestation instead of making one. | -| `if_match_sha256` | `str` | `''` | The `content_sha256` of the read being attested or revoked: another live hash answers 409 `PRECONDITION_FAILED` and writes nothing; '' checks nothing. | +| `if_match_sha256` | `str` | `''` | The `content_sha256` `memory.get` or `memory.get_by_id` returned for the content being attested or revoked: another live hash answers 409 `PRECONDITION_FAILED` and writes nothing; '' checks nothing. | | `actor` | `str` | `''` | Attester recorded when the server runs without auth (`human:` / `process:` + subject); under auth the token decides. | | Output field | Type | Meaning | diff --git a/docs/reference/python-sdk.md b/docs/reference/python-sdk.md index b848e4caabf..fbb79eb2fde 100644 --- a/docs/reference/python-sdk.md +++ b/docs/reference/python-sdk.md @@ -415,7 +415,7 @@ whose body has neither, or one the SDK raised itself: | `AuthInvalid` | `AUTH_INVALID`; status 401 | | | `AuthInsufficient` | `AUTH_INSUFFICIENT`; status 403 | | | `NotFound` | `RESOURCE_NOT_FOUND`; status 404 | | -| `PreconditionFailed` | `PRECONDITION_FAILED`; status 409, 412 without a known code | `.current_sha256`: retry without re-reading | +| `PreconditionFailed` | `PRECONDITION_FAILED`; status 409, 412 without a known code | `.current_sha256`: a write retries without re-reading; `memory.verify` and a definition approval read again first | | `IdempotentConflict` | `IDEMPOTENT_CONFLICT` | | | `WrongCell` | `WRONG_CELL` | subclass of `PreconditionFailed`; `.org` and `.cell` (the org's cell, or ''): look its host up with the router's `GET /cells/lookup` | | `BackendUnavailable` | `BACKEND_UNAVAILABLE`, any 5xx, and `NETWORK` (no response) | `cannot reach : …`, `no response from : …` (a write that broke off, a timeout), or `response from cut off: …` | diff --git a/sdk/python/loom/errors.py b/sdk/python/loom/errors.py index 818dadcc9f8..5de9645a69d 100644 --- a/sdk/python/loom/errors.py +++ b/sdk/python/loom/errors.py @@ -222,9 +222,10 @@ class PreconditionFailed(LoomError): (retry the restore; no hash). A mismatch carries the server's current hash in `.current_sha256` so a caller - can re-read and retry without an extra get round-trip. For a definition's - `approved_sha256`, show the current text again and approve that: never resend - `.current_sha256` unseen. Any 409 the SDK has no class for (such as + can re-read and retry without an extra get round-trip. For `memory.verify` and + a definition's `approved_sha256`, read the current text again and attest or + approve that: never resend `.current_sha256` unseen (`memory.verify` sends + none for a `high` row). Any 409 the SDK has no class for (such as `DEFINITION_NAME_TAKEN`) arrives as this class, with no hash: check `.code`. """ diff --git a/sdk/python/loom/memory.py b/sdk/python/loom/memory.py index 783316cbb85..0f4928a3205 100644 --- a/sdk/python/loom/memory.py +++ b/sdk/python/loom/memory.py @@ -1123,9 +1123,11 @@ async def verify( by a dev-mode server with no auth context. Address by `memory_key` (with this Agent's identity) or `memory_id`. - Pass `if_match_sha256`, the `content_sha256` of the read being attested - or revoked, and the server raises `PreconditionFailed` (409) when the row - holds other content. + Pass `if_match_sha256`, the `content_sha256` that `get()` or `get_by_id()` + returned for the content being attested or revoked, and the server raises + `PreconditionFailed` (409) when the row holds other content. On + `PreconditionFailed` read the row again and attest what it says; never + resend `.current_sha256` unread. Returns the server's `MemoryVerifyOutput` dict: `found`, `changed`, `verified_by`, `verified_at`, `verification` (human | process | stale | none), `content_sha256`. diff --git a/server/memory/api/models_crud.py b/server/memory/api/models_crud.py index 9db82630e4a..1b4c8ed43c1 100644 --- a/server/memory/api/models_crud.py +++ b/server/memory/api/models_crud.py @@ -1310,8 +1310,9 @@ class MemoryVerifyInput(BaseModel): memory_key: str = "" # True clears the attestation instead of making one. revoke: bool = False - # The `content_sha256` of the read being attested or revoked: another live hash - # answers 409 `PRECONDITION_FAILED` and writes nothing; '' checks nothing. + # The `content_sha256` `memory.get` or `memory.get_by_id` returned for the content + # being attested or revoked: another live hash answers 409 `PRECONDITION_FAILED` + # and writes nothing; '' checks nothing. if_match_sha256: str = "" # Attester recorded when the server runs without auth (`human:` / `process:` + # subject); under auth the token decides. diff --git a/server/memory/app/verify.py b/server/memory/app/verify.py index d31b8e50690..6ddf9d3f512 100644 --- a/server/memory/app/verify.py +++ b/server/memory/app/verify.py @@ -17,6 +17,7 @@ cannot reach reads as not found. * `if_match_sha256` names the content the caller read: another live hash answers 409 before anything is written, for an attestation and a revoke alike. + The 409 carries the live hash, except for a `high` row. * A new ReplacingMergeTree version row is written through `build_memory_version_row`, carrying every column forward; the three attestation columns and `content_sha256` are the only deltas. The @@ -151,7 +152,8 @@ async def handle_memory_verify(input: MemoryVerifyInput) -> MemoryVerifyOutput: raise PreconditionFailedError( "the memory holds other content than if_match_sha256 names; " "read it again before attesting or revoking", - current_sha256=sha, + # The hash of a short secret names it: only the audited read serves it. + current_sha256="" if row.sensitivity == "high" else sha, ) before = trust.verification_state(row.verified_by, row.verified_sha256, sha) diff --git a/server/transport/arg_check.py b/server/transport/arg_check.py index 5a72226cdaa..9f8b29d871b 100644 --- a/server/transport/arg_check.py +++ b/server/transport/arg_check.py @@ -122,14 +122,15 @@ def private_argument_names_fit(model: type[BaseModel], args: dict[str, Any]) -> return True -# Synonyms models send for a field the op has (seen in session transcripts -# and the `ignored_args` log). A synonym only counts where the op has the -# target field. +# Synonyms a caller sends for a field the op has: seen in session transcripts +# and the `ignored_args` log, or the name a read serves the value under. A +# synonym only counts where the op has the target field. SYNONYMS: dict[str, tuple[str, ...]] = { "query": ("text",), # tracker.similar "text": ("addition",), # working_memory.append "limit": ("top_k",), # tracker.similar "key_prefix": ("prefix",), # memory.list + "content_sha256": ("if_match_sha256",), # the name a read serves the hash under } # Prefixes a model adds to a field's name that the field itself leaves off # ("memory_keys" for ApplyTarget.keys, "key_prefix" for prefix). diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index e3e91b28f25..cffa4030569 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -502,8 +502,9 @@ def revision_policy(update: str) -> str: "Attest that a memory is TRUE, as the signed-in person (or revoke " "that attestation). Use only when the user explicitly confirms a " "fact ('yes, that's right', 'mark that as verified') — never on your " - "own judgement. Send if_match_sha256, the content_sha256 of the read " - "the user confirmed; a 409 means the memory changed: show the current " + "own judgement. Send if_match_sha256, the content_sha256 memory.get " + "returned with the text the user confirmed (a search hit carries none); " + "a 409 means the memory changed: show the current " "text and ask again, never resend the returned hash unseen. " "The attestation binds to the memory's content: a " "later edit shows it as `stale` until re-verified. Address by " diff --git a/tests/unit/session_content_senders.json b/tests/unit/session_content_senders.json index 9194b99310d..c9722fedf4f 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -426,7 +426,7 @@ "sdk/python/loom/integrations/langgraph.py": "5d68e6ab1645d868477a13b14aa6d734c72f72057464cac9a21aa707add17e7b", "sdk/python/loom/integrations/llamaindex.py": "06eaa071115cad752d27bdc9bf7c4d5b6f5d7d39d9896267fcd459a4e06bf661", "sdk/python/loom/integrations/openai_agents.py": "143fe1df060b96550a33f77fa44416e291c2154552e433f8309275f61c8fca2a", - "sdk/python/loom/memory.py": "46ead264f3287a801f39c784f832909599806a8abbd84cb766100dec80110c35", + "sdk/python/loom/memory.py": "871341cf30213df5830f160c5219df3713db84418883cceeb1765c46b215f0bf", "sdk/python/loom/run.py": "e8a226167889f9657f93ffa9b00b46cdda70de49ce236c07da1124a2f23b3832", "sdk/python/loom/session.py": "5f0fd61fcfdbf9d60888b111887fca8f32e24eb51ca9ff04a256901657c3202b", "sdk/typescript/src/integrations/claude-memory.ts": "c846f0011d7cf1ba4b30e99fbfd8adb6b29abff56856d0dbe14fba620007f6bc", diff --git a/tests/unit/test_arg_feedback.py b/tests/unit/test_arg_feedback.py index ef87204dec2..51f7c8794da 100644 --- a/tests/unit/test_arg_feedback.py +++ b/tests/unit/test_arg_feedback.py @@ -85,6 +85,35 @@ def test_the_silent_working_memory_delete_is_now_refused() -> None: assert detail["code"] == "UNKNOWN_ARGUMENT" and detail["did_you_mean"] == {"block": "block_key"} +@pytest.mark.parametrize( + "op_name", + [ + "memory.verify", + "memory.set", + "memory.update", + "memory.update_by_id", + "memory.move", + "memory.pin", + "profile.set", + ], +) +def test_a_hash_under_the_name_a_read_serves_it_is_refused_not_dropped(op_name: str) -> None: + """Served, the write would run with no precondition: `memory.verify` would attest + whatever the row holds.""" + refused = arg_check.named_argument_error( + OPERATIONS_BY_NAME[op_name], + {"org": "o", "namespace": "n", "agent": "a", "memory_key": "k", "content_sha256": "0" * 64}, + ) + assert refused is not None + detail = refused.error_detail() + assert detail["code"] == "UNKNOWN_ARGUMENT" + assert detail["did_you_mean"] == {"content_sha256": "if_match_sha256"} + + +def test_a_hash_gets_no_guess_where_the_op_takes_no_precondition() -> None: + assert arg_check.did_you_mean(_model("memory.delete"), ["content_sha256"]) == {} + + # ----------------------------------------------------- the feedback block diff --git a/tests/unit/test_memory_verify.py b/tests/unit/test_memory_verify.py index 1699dd32cfc..a7e78123fa8 100644 --- a/tests/unit/test_memory_verify.py +++ b/tests/unit/test_memory_verify.py @@ -390,6 +390,25 @@ async def test_another_hash_than_the_live_one_is_refused_and_writes_nothing( assert ch.inserted == [] and scheduled == [] +@pytest.mark.asyncio +async def test_a_refusal_on_a_high_row_carries_no_hash(monkeypatch: pytest.MonkeyPatch) -> None: + """The refusal writes no audit row, so it serves nothing the audited read serves.""" + row = _row(sensitivity="high") + ch = _wire(monkeypatch, row) + scheduled = _record_mirrors(monkeypatch) + set_current_auth(_token("alice")) + + with pytest.raises(PreconditionFailedError) as ei: + await mv.handle_memory_verify( + MemoryVerifyInput( + org="o", memory_id=row.memory_id, if_match_sha256=_sha("what alice read") + ) + ) + + assert ei.value.extra["current_sha256"] == "" + assert ch.inserted == [] and scheduled == [] + + @pytest.mark.asyncio async def test_the_live_hash_attests(monkeypatch: pytest.MonkeyPatch) -> None: row = _row() From ff85a8e75d446990400a1766053bcfde89e32c93 Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Fri, 4 Dec 2026 23:54:25 +0000 Subject: [PATCH 3/5] The memory drawer says when a verify finds no row, and its refused-verify line carries the request id `memory.verify` answers 200 `found=false` for a row deleted after the drawer read it. The drawer did not read `found`: it showed "Verified as " with no name and kept the deleted row on screen. It says the memory is gone and reads it again, as Unlock and Delete do. The line for a 409 was a plain info toast: 3.5 s and no request id. The dashboard design guide sends a page's own line about a refused call through `toastWithId`, which gives it the request id and an error's reading time. The line is the only cue that the content changed under the reader. The drawer test for the 409 gave the refusal and the re-read the same hash, so it could not tell which one the retry sent, and its retry click had no answer of its own. The re-read returns a third hash, the retry is answered, and the test waits for the success toast. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- .../MemoryInspector.lifecycle.test.tsx | 48 +++++++++++++++---- frontend/src/components/MemoryInspector.tsx | 10 +++- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/frontend/src/components/MemoryInspector.lifecycle.test.tsx b/frontend/src/components/MemoryInspector.lifecycle.test.tsx index 32a4b66e201..1e6b0e7c8b6 100644 --- a/frontend/src/components/MemoryInspector.lifecycle.test.tsx +++ b/frontend/src/components/MemoryInspector.lifecycle.test.tsx @@ -28,7 +28,12 @@ const LIVE: MemoryDetail = { user_id: "alice", }; -vi.mock("./Toast", () => ({ toast: vi.fn(), toastError: vi.fn(), ToastViewport: () => null })); +vi.mock("./Toast", () => ({ + toast: vi.fn(), + toastError: vi.fn(), + toastWithId: vi.fn(), + ToastViewport: () => null, +})); vi.mock("./ConfirmDialog", () => ({ confirmAction: vi.fn(async () => true), ConfirmViewport: () => null })); vi.mock("../api", async (importOriginal) => { @@ -79,7 +84,7 @@ vi.mock("../api/memoryLifecycle", () => ({ import * as api from "../api"; import * as lc from "../api/memoryLifecycle"; import { confirmAction } from "./ConfirmDialog"; -import { toast, toastError } from "./Toast"; +import { toast, toastError, toastWithId } from "./Toast"; const grant = (role: MyNamespaceEntry["role"]): MyNamespaceEntry => ({ namespace: "team", @@ -377,25 +382,35 @@ describe("MemoryInspector lifecycle actions", () => { }); it("reads the memory again when a verify is refused because the content changed", async () => { - vi.mocked(api.verifyMemory).mockRejectedValueOnce( - new ApiError({ status: 409, code: "PRECONDITION_FAILED", detail: { current_sha256: "def" } }), - ); + const refused = new ApiError({ status: 409, code: "PRECONDITION_FAILED", detail: { current_sha256: "def" } }); + vi.mocked(api.verifyMemory).mockRejectedValueOnce(refused); await open("writer", { ...LIVE, content_sha256: "abc" }); - vi.mocked(api.getMemory).mockResolvedValue({ ...LIVE, value: "oat milk, one sugar", content_sha256: "def" }); + vi.mocked(api.getMemory).mockResolvedValue({ ...LIVE, value: "oat milk, one sugar", content_sha256: "ghi" }); await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); await waitFor(() => - expect(toast).toHaveBeenCalledWith( + expect(toastWithId).toHaveBeenCalledWith( "This memory changed since it was opened. Check the current content, then try again.", "info", + refused, ), ); expect(await screen.findByText("oat milk, one sugar")).toBeInTheDocument(); expect(toastError).not.toHaveBeenCalled(); // The next try attests the text now shown, never the hash the refusal returned unread. + vi.mocked(api.verifyMemory).mockResolvedValueOnce({ + found: true, + changed: true, + verified_by: "human:o@example.com", + verified_at: "2026-09-18T10:00:00Z", + verification: "human", + content_sha256: "ghi", + }); await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); await waitFor(() => - expect(api.verifyMemory).toHaveBeenLastCalledWith(row, "coffee_pref", { revoke: false, ifMatchSha256: "def" }), + expect(api.verifyMemory).toHaveBeenLastCalledWith(row, "coffee_pref", { revoke: false, ifMatchSha256: "ghi" }), ); + await waitFor(() => expect(toast).toHaveBeenCalledWith("Verified as human:o@example.com", "ok")); + expect(toastError).not.toHaveBeenCalled(); cleanup(); const down = new ApiError({ status: 503, code: "ADMISSION_CONTENDED" }); @@ -405,6 +420,23 @@ describe("MemoryInspector lifecycle actions", () => { await waitFor(() => expect(toastError).toHaveBeenCalledWith("Verify failed", down)); }); + it("says a memory is gone when the verify finds no row", async () => { + vi.mocked(api.verifyMemory).mockResolvedValueOnce({ + found: false, + changed: false, + verified_by: "", + verified_at: null, + verification: "none", + content_sha256: "", + }); + await open("writer", { ...LIVE, content_sha256: "abc" }); + vi.mocked(api.getMemory).mockResolvedValue({ ...LIVE, found: false }); + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); + await waitFor(() => expect(toast).toHaveBeenCalledWith("This memory is no longer live", "info")); + expect(await screen.findByText("Memory not found. It may have been deleted.")).toBeInTheDocument(); + expect(toast).not.toHaveBeenCalledWith(expect.stringContaining("Verified as"), "ok"); + }); + it("says why a share was refused", async () => { vi.mocked(lc.shareMemory).mockRejectedValueOnce(new Error("a shared memory already holds this key")); await open("admin"); diff --git a/frontend/src/components/MemoryInspector.tsx b/frontend/src/components/MemoryInspector.tsx index 3ac20a7c92a..2e5150e5935 100644 --- a/frontend/src/components/MemoryInspector.tsx +++ b/frontend/src/components/MemoryInspector.tsx @@ -57,7 +57,7 @@ import { graphSeedHref, isModifiedClick, openGraphAt } from "../lib/graphLink"; import { ApiError, isPublicationPending } from "../lib/errors"; import { AgentBadge } from "./AgentBadge"; import { DiffView } from "./DiffView"; -import { keepOpenOnToasts, toast, toastError } from "./Toast"; +import { keepOpenOnToasts, toast, toastError, toastWithId } from "./Toast"; import { committedAnyway, errorLine, toastCommitted } from "../lib/errorWords"; import { IconButton } from "./IconButton"; import { SkeletonText } from "./Skeleton"; @@ -577,13 +577,19 @@ export function MemoryInspector({ revoke: live, ifMatchSha256: detail.content_sha256, }); + if (!r.found) { + // The row went after the drawer read it: nothing was attested or revoked. + toast("This memory is no longer live", "info"); + await reread(); + return; + } setDetail({ ...detail, verified_by: r.verified_by, verified_at: r.verified_at, verification: r.verification }); toast(live ? "Verification removed" : `Verified as ${r.verified_by}`, "ok"); onChanged(); } catch (e) { if (e instanceof ApiError && e.status === 409 && e.code === "PRECONDITION_FAILED") { // The row holds other content than the drawer shows: show what it holds. - toast("This memory changed since it was opened. Check the current content, then try again.", "info"); + toastWithId("This memory changed since it was opened. Check the current content, then try again.", "info", e); await reread(); return; } From 5e027347500adc1bc59b83f503706c80107315ac Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sat, 5 Dec 2026 00:36:01 +0000 Subject: [PATCH 4/5] content_sha256 is no argument synonym: every op that takes if_match_sha256 serves the key `SYNONYMS` in `server/transport/arg_check.py` is not keyed by op. The entry that read `content_sha256` as `if_match_sha256` therefore refused the key with 422 `UNKNOWN_ARGUMENT` on every op that takes the precondition: `memory.verify`, and also `memory.set`, `memory.update`, `memory.update_by_id`, `memory.move`, `memory.pin` and `profile.set`, which serve the key on `main` and name it in `ignored_args`. Four of those six are `stable`. That is a wire break on ops this change does not concern: it adds one optional field to `memory.verify` and changes no default. The entry, its two tests and its sentence in the writing page are removed. Refusing the key is its own change, with the break in its title and under its own changelog category. `memory.verify` treats a hash sent as `content_sha256` as any unknown key: it answers 200, names the key in `ignored_args` and checks no precondition. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- docs/features/memory/writing.md | 10 ++++------ server/transport/arg_check.py | 7 +++---- tests/unit/test_arg_feedback.py | 29 ----------------------------- 3 files changed, 7 insertions(+), 39 deletions(-) diff --git a/docs/features/memory/writing.md b/docs/features/memory/writing.md index 9908808c604..b292fd5905d 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -148,12 +148,10 @@ async with Agent(org="acme", namespace="support", agent="triage-bot") as agent: `memory.update`, `memory.update_by_id` and `memory.move` (source row) accept the same precondition. [`memory.verify`](./history-and-provenance.md#attestation-memoryverify) accepts it for the row being attested or revoked, and takes the hash a `memory.get` or -`memory.get_by_id` read returned. A write that carries the hash as `content_sha256`, the -name a read serves it under, is refused with 422 `UNKNOWN_ARGUMENT`, which names -`if_match_sha256`. The Python SDK coalesces a burst of `set` calls from one identity -into one `memory.bulk_set` (from the third set inside 200 ms); a coalesced result carries -`coalesced: true` and no `content_sha256`. A set with `if_match_sha256` is never -coalesced. +`memory.get_by_id` read returned. The Python SDK coalesces a burst of `set` calls from +one identity into one `memory.bulk_set` (from the third set inside 200 ms); a coalesced +result carries `coalesced: true` and no `content_sha256`. A set with `if_match_sha256` +is never coalesced. A `memory.set` or `memory.update` that carries the precondition holds a lock on its key from the check to the insert, so of two writers holding the same hash only one succeeds. diff --git a/server/transport/arg_check.py b/server/transport/arg_check.py index 9f8b29d871b..5a72226cdaa 100644 --- a/server/transport/arg_check.py +++ b/server/transport/arg_check.py @@ -122,15 +122,14 @@ def private_argument_names_fit(model: type[BaseModel], args: dict[str, Any]) -> return True -# Synonyms a caller sends for a field the op has: seen in session transcripts -# and the `ignored_args` log, or the name a read serves the value under. A -# synonym only counts where the op has the target field. +# Synonyms models send for a field the op has (seen in session transcripts +# and the `ignored_args` log). A synonym only counts where the op has the +# target field. SYNONYMS: dict[str, tuple[str, ...]] = { "query": ("text",), # tracker.similar "text": ("addition",), # working_memory.append "limit": ("top_k",), # tracker.similar "key_prefix": ("prefix",), # memory.list - "content_sha256": ("if_match_sha256",), # the name a read serves the hash under } # Prefixes a model adds to a field's name that the field itself leaves off # ("memory_keys" for ApplyTarget.keys, "key_prefix" for prefix). diff --git a/tests/unit/test_arg_feedback.py b/tests/unit/test_arg_feedback.py index 51f7c8794da..ef87204dec2 100644 --- a/tests/unit/test_arg_feedback.py +++ b/tests/unit/test_arg_feedback.py @@ -85,35 +85,6 @@ def test_the_silent_working_memory_delete_is_now_refused() -> None: assert detail["code"] == "UNKNOWN_ARGUMENT" and detail["did_you_mean"] == {"block": "block_key"} -@pytest.mark.parametrize( - "op_name", - [ - "memory.verify", - "memory.set", - "memory.update", - "memory.update_by_id", - "memory.move", - "memory.pin", - "profile.set", - ], -) -def test_a_hash_under_the_name_a_read_serves_it_is_refused_not_dropped(op_name: str) -> None: - """Served, the write would run with no precondition: `memory.verify` would attest - whatever the row holds.""" - refused = arg_check.named_argument_error( - OPERATIONS_BY_NAME[op_name], - {"org": "o", "namespace": "n", "agent": "a", "memory_key": "k", "content_sha256": "0" * 64}, - ) - assert refused is not None - detail = refused.error_detail() - assert detail["code"] == "UNKNOWN_ARGUMENT" - assert detail["did_you_mean"] == {"content_sha256": "if_match_sha256"} - - -def test_a_hash_gets_no_guess_where_the_op_takes_no_precondition() -> None: - assert arg_check.did_you_mean(_model("memory.delete"), ["content_sha256"]) == {} - - # ----------------------------------------------------- the feedback block From 75c26a9a569cd5c9c43e581d881fa13129a3730b Mon Sep 17 00:00:00 2001 From: Mohammad Lareb Zafar Date: Sat, 5 Dec 2026 00:36:06 +0000 Subject: [PATCH 5/5] The comment on memory.verify's refusal of a high row states the rule the handler keeps The comment said only the audited read serves the hash of a `high` row. The handler's 200 answers return `content_sha256` for a `high` row under the op's own `memory.verify` audit row, with no `memory.sensitive_read` row. The rule the branch keeps is narrower: a refusal leaves no audit row, so it carries no hash of a `high` row. The comment says that. Signed-off-by: Mohammad Lareb Zafar Co-Authored-By: Claude Fable 5.2 --- server/memory/app/verify.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/memory/app/verify.py b/server/memory/app/verify.py index 6ddf9d3f512..906874bdaae 100644 --- a/server/memory/app/verify.py +++ b/server/memory/app/verify.py @@ -152,7 +152,7 @@ async def handle_memory_verify(input: MemoryVerifyInput) -> MemoryVerifyOutput: raise PreconditionFailedError( "the memory holds other content than if_match_sha256 names; " "read it again before attesting or revoking", - # The hash of a short secret names it: only the audited read serves it. + # A refusal leaves no audit row, so it carries no hash of a `high` row. current_sha256="" if row.sensitivity == "high" else sha, ) before = trust.verification_state(row.verified_by, row.verified_sha256, sha)