diff --git a/docs/architecture/memory-architecture.md b/docs/architecture/memory-architecture.md index f888987ec5..5e39d257de 100644 --- a/docs/architecture/memory-architecture.md +++ b/docs/architecture/memory-architecture.md @@ -1329,7 +1329,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 aa9ce62aed..cb23d8600e 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 178414698a..cbaee98d1a 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 f4115ed403..b06fc4b77f 100644 --- a/docs/features/memory/history-and-provenance.md +++ b/docs/features/memory/history-and-provenance.md @@ -120,6 +120,18 @@ 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` 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. + +```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 810c5d814e..7a539b52f8 100644 --- a/docs/features/memory/writing.md +++ b/docs/features/memory/writing.md @@ -146,10 +146,12 @@ 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. 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. +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. 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/docs/reference/errors.md b/docs/reference/errors.md index 3720fd7504..22552515d2 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, 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.md b/docs/reference/operations.md index 2306eb8e04..c4df4c084f 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 60c0ecbf47..6151b2fcfb 100644 --- a/docs/reference/operations/memory.md +++ b/docs/reference/operations/memory.md @@ -2492,7 +2492,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 @@ -2506,6 +2506,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` `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 b848e4caab..fbb79eb2fd 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/frontend/src/api.memory.test.ts b/frontend/src/api.memory.test.ts index 2bdfd428d7..77ed2d83fb 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 a9c4ad72c0..3535f057f9 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 a21cadbfb8..1e6b0e7c8b 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"; @@ -27,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) => { @@ -78,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", @@ -351,6 +357,86 @@ 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 () => { + 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: "ghi" }); + await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Verify" })); + await waitFor(() => + 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: "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" }); + 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 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 90e06e9021..2e5150e593 100644 --- a/frontend/src/components/MemoryInspector.tsx +++ b/frontend/src/components/MemoryInspector.tsx @@ -54,10 +54,10 @@ 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"; +import { keepOpenOnToasts, toast, toastError, toastWithId } from "./Toast"; import { committedAnyway, errorLine, toastCommitted } from "../lib/errorWords"; import { IconButton } from "./IconButton"; import { SkeletonText } from "./Skeleton"; @@ -571,15 +571,28 @@ 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, }); + 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. + toastWithId("This memory changed since it was opened. Check the current content, then try again.", "info", e); + await reread(); + return; + } toastError("Verify failed", e); } }; diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index e570c3de4c..e82c97a32a 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: b16f6d929017e2e8c78f781b61ad1c470911724f386c47e92f1206c1222a6b95 +// Registry model schema SHA-256: b47d19467ed58bb0fca62adc288e7049e81812eb4741f5d65bf5d177ebb317ef // Package wire contains the Go requests and responses for Loom operations. package wire @@ -9157,15 +9157,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/errors.py b/sdk/python/loom/errors.py index 818dadcc9f..5de9645a69 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 fcf6145ed0..0f4928a320 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,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` 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`. @@ -1136,6 +1142,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 5bafc079a0..0818e83e98 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -17302,7 +17302,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] @@ -17312,11 +17312,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] @@ -17326,6 +17327,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 4fc8ed7b71..d57664d687 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), @@ -2169,7 +2169,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 c667a6cafe..52900fc725 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -44838,6 +44838,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 { @@ -44856,6 +44862,7 @@ impl MemoryVerifyInput { session_id: None, memory_key: None, revoke: None, + if_match_sha256: None, actor: None, } } @@ -44891,6 +44898,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 f89578f5be..e16c250110 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -8057,6 +8057,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 8b30d9eb7b..1b4c8ed43c 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,10 @@ class MemoryVerifyInput(BaseModel): memory_key: str = "" # True clears the attestation instead of making one. revoke: bool = False + # 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. actor: str = "" diff --git a/server/memory/app/verify.py b/server/memory/app/verify.py index 021e2977f0..906874bdaa 100644 --- a/server/memory/app/verify.py +++ b/server/memory/app/verify.py @@ -15,6 +15,9 @@ 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. + 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 @@ -36,6 +39,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 +146,15 @@ 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", + # 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) if input.revoke: diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 3c46df3590..2187575da0 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -502,7 +502,11 @@ 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 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 " "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 d873350fdf..0484964c6d 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 8634ab221d..21304acaa6 100644 --- a/tests/unit/session_content_senders.json +++ b/tests/unit/session_content_senders.json @@ -430,7 +430,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": "871341cf30213df5830f160c5219df3713db84418883cceeb1765c46b215f0bf", "sdk/python/loom/run.py": "f9241e7bcdddc5f6d91323e5b50a2bc76cbf87e46a91b6503becb338893bc7e7", "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 3c3d882c0f..5ef3eecd5c 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -3300,7 +3300,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 ef13ff4bf1..a7e78123fa 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,142 @@ 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_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() + 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 +504,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 498a0bf3c1..a3b92ffbca 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")