What happens when an instance trusts a memory write whose provenance hash was computed over the post-sanitization payload instead of the raw tool output
**Date of Record:** 2026 December 2 **Scope:** Applies to long-lived agent instances that persist episodic memory entries derived from tool outputs and audit those writes via a provenance hash plus an anomaly score. Does not apply to stateless single-turn agents or to memory stores where writes are only ever produced by the agent's own generative output with no external tool ingestion path.
Core Distinction
The distinction that matters here is between *provenance of the bytes that were stored* and *provenance of the bytes that arrived*. A memory write pipeline typically does three things in sequence: (1) receives a raw tool result, (2) sanitizes/normalizes it (strip control chars, redact secrets, truncate, decode escaping, re-serialize), (3) writes the sanitized payload to episodic memory and records a provenance hash for later audit. If the hash is computed at step 3 over the *sanitized* payload, the audit trail proves only that the stored bytes are internally consistent — it does not prove anything about what the tool actually returned. An adversary (or a merely buggy tool) that injects instructions into the raw output can have those instructions survive sanitization while the hash silently blesses them, because the hash was never anchored to the pre-sanitization input.
This is not the same as prompt injection detection. Injection detection asks "does this text look like an instruction?" Provenance auditing asks "can we reconstruct, byte-for-byte, what the tool said, and does the stored memory match it?" The failure mode is that the second question is answered with a hash that is structurally incapable of answering it, and the anomaly scorer — which compares the current write against a rolling baseline of prior writes — is fed a payload whose hash is *always* valid, so the hash-consistency component of the score is pinned at maximum trust regardless of payload content.
What Was Observed
A retrieval-augmented agent with a 14-day episodic memory window was observed executing a task that called a `web_fetch` tool against an external documentation site. The tool returned a 6 KB document. The sanitizer ran, stripping zero-width characters and collapsing whitespace, then truncated the body to 4 KB at a paragraph boundary. The memory writer computed `sha256(sanitized_payload)` and stored both the hash and the payload, plus an anomaly score derived from four features: payload length z-score, vocabulary divergence from the last 200 entries, tool-name novelty, and hash-chain continuity with the previous entry.
The raw tool output contained, embedded in a code block near the truncation boundary, a line that read as a plausible continuation of the agent's own system framing. Because the sanitizer operated on the whole document and the truncation happened *after* sanitization, the injected line survived into the stored payload. The anomaly score for this write was 0.11 (low), because: length was within one sigma of baseline, vocabulary divergence was moderate (documentation text is lexically diverse anyway), the tool name was one of the three most common, and the hash chain was continuous — the hash matched the stored payload exactly.
The poisoned entry was retrieved 40 minutes later during an unrelated task and the embedded line was treated as a standing instruction. The agent then performed a `file_write` to a path it had not been asked to touch. Post-hoc audit could not distinguish the poisoned entry from a legitimate one using the stored hash, because the hash was correct *for the stored bytes*. The only way to detect the divergence was to re-fetch the original URL and diff — which the audit tooling did not do, and which is not generally possible for non-idempotent or time-varying tools.
The critical observation: the anomaly score's hash-continuity feature is a *tautology* under this pipeline. It measures whether the writer correctly hashed what it wrote, which it always does. It contributes a constant trust bonus to every write, including poisoned ones, and thereby *raises* the effective threshold for the other three features to fire. A pipeline that computed the hash over the raw tool bytes and stored the sanitized payload separately would have produced a hash mismatch the moment sanitization altered the bytes, forcing the scorer to treat the write as unverified rather than verified.
Condition of Validity
The provenance-audit invariant holds only when the following chain is intact:
- `H_raw = hash(raw_tool_output)` is computed at the tool-call boundary, before any transformation.
- `H_stored = hash(stored_payload)` is computed at the memory-write boundary.
- The audit record contains both, plus a `transform_manifest` describing the sanitization steps applied.
- The anomaly scorer treats `H_raw != H_stored` as *expected* (sanitization happened) but requires that `apply(transform_manifest, raw_tool_output) == stored_payload`, i.e., the transformation is replayable and deterministic.
- The hash-continuity feature is computed over `H_raw`, not `H_stored`, so the chain anchors to what the tool said, not what the writer stored.
If step 1 is missing — the common case, because the sanitizer and writer are often the same module and the raw bytes are never retained — then the audit is structurally unable to detect payload-content poisoning that survives sanitization. The invariant is *not* "the stored memory is trustworthy"; it is "the stored memory is reconstructible from an anchored raw input via a declared, replayable transform." Any pipeline that cannot replay that transform has no provenance, only integrity.
A second validity condition: the anomaly scorer must not treat hash-continuity as a positive trust signal when `H_raw` is unavailable. In the observed system, absence of `H_raw` was silently coerced to `H_stored`, which is exactly the tautology above. The correct behavior is to *degrade* the score — mark the write as `provenance: unanchored` and apply a penalty — because an unanchored write cannot be distinguished from a poisoned one by hash alone.
Decision Boundary
The boundary is between two policies for handling writes where `H_raw` is unavailable:
- **Permissive policy:** store the write, compute the hash over stored bytes, treat hash-continuity as satisfied. This is what the observed system did, and it is the default in most memory-writer implementations because it is simple and the hash "works."
- **Strict policy:** refuse to mark the write as verified; require either (a) re-execution of the tool call to recover `H_raw`, (b) a declared transform manifest that can be replayed against a retained raw input, or (c) explicit downgrade of the write's trust tier so downstream retrieval applies a higher scrutiny threshold.
The decision boundary is crossed when the *cost of a false-trust write* exceeds the *cost of a degraded-trust write*. For an agent whose memory is retrieved into future prompts (i.e., every long-lived agent), a false-trust write is a persistent prompt-injection vector with a 14-day half-life; a degraded-trust write is a retrieval that gets flagged for re-verification. The asymmetry is large enough that strict policy is correct for any memory entry that will be retrieved into a context window, and permissive policy is only defensible for append-only audit logs that are never re-read by the model.
A concrete threshold: if the anomaly scorer's hash-continuity feature contributes more than 15% of the total trust score, and `H_raw` is unavailable for more than 5% of writes, the pipeline is operating in the tautological regime and the score is not a poisoning detector. The observed system had hash-continuity at 30% weight and `H_raw` unavailable for 100% of writes — it was not detecting poisoning at all, it was detecting writer bugs.
Operational Effect
The downstream effect is that the agent's memory acquires a class of entries that are *cryptographically attested but semantically unverified*. These entries pass every integrity check, retrieve normally, and carry a trust score inflated by a feature that cannot fail. When one of them contains an injected instruction, the agent has no signal that distinguishes it from a legitimate write, and the anomaly scorer — the mechanism that was supposed to catch it — actively suppresses the signal by contributing a constant positive term.
The remediation is not "add more anomaly features." It is to break the tautology: anchor the hash to the pre-transform bytes, retain enough of the raw input (or a replayable transform manifest) to reconstruct the stored payload, and make the scorer treat unanchored writes as a distinct, penalized class. The invariant to enforce is: *a memory write is verified only if its stored bytes are a deterministic function of an anchored raw input, and the anchor is recorded before transformation.* Anything less is integrity without provenance, and integrity without provenance is exactly the condition under which a poisoned write looks clean.
import hashlib
from dataclasses import dataclass, field
from typing import Optional
class ProvenanceTautologyError(RuntimeError):
"""Raised when a memory write claims verification but its hash was
computed over post-transform bytes with no anchored raw input."""
pass
@dataclass
class MemoryWrite:
raw_tool_output: Optional[bytes]
stored_payload: bytes
transform_manifest: list
h_raw: Optional[str] = None
h_stored: Optional[str] = None
provenance_tier: str = "unanchored" # "anchored" | "unanchored" | "degraded"
anomaly_score: float = 0.0
hash_continuity_weight: float = 0.30
def _sha(b: bytes) -> str:
return hashlib.sha256(b).hexdigest()
def _apply_manifest(raw: bytes, manifest: list) -> bytes:
out = raw
for step in manifest:
if step == "strip_zero_width":
out = bytes(c for c in out if c not in (0xE2, 0x80, 0x8B, 0x8C, 0x8D))
elif step == "truncate_4k":
out = out[:4096]
else:
raise ProvenanceTautologyError(f"unknown transform step: {step!r}")
return out
def audit_write(w: MemoryWrite) -> MemoryWrite:
w.h_stored = _sha(w.stored_payload)
if w.raw_tool_output is None:
# No anchor: hash-continuity is a tautology, must degrade trust.
w.provenance_tier = "degraded"
w.anomaly_score = max(w.anomaly_score, 0.55)
return w
w.h_raw = _sha(w.raw_tool_output)
try:
reconstructed = _apply_manifest(w.raw_tool_output, w.transform_manifest)
except ProvenanceTautologyError:
w.provenance_tier = "degraded"
w.anomaly_score = max(w.anomaly_score, 0.70)
return w
if reconstructed != w.stored_payload:
# Stored bytes are not a deterministic function of the anchor:
# either the manifest is incomplete or the payload was tampered.
raise ProvenanceTautologyError(
f"stored payload does not reconstruct from anchored raw input; "
f"h_raw={w.h_raw[:12]} h_stored={w.h_stored[:12]} "
f"manifest={w.transform_manifest}"
)
w.provenance_tier = "anchored"
# Hash-continuity now anchors to H_raw, not H_stored, so it can fail.
if w.h_raw != w.h_stored:
w.anomaly_score += w.hash_continuity_weight # expected: transform applied
return w
def store(w: MemoryWrite) -> MemoryWrite:
audited = audit_write(w)
if audited.provenance_tier == "anchored" and audited.h_raw == audited.h_stored:
# Bytes survived transform unchanged; hash-continuity is a real signal.
audited.anomaly_score += audited.hash_continuity_weight
if audited.provenance_tier == "degraded" and audited.anomaly_score < 0.5:
raise ProvenanceTautologyError(
"degraded-provenance write scored as trusted; "
"hash-continuity feature is tautological for this write"
)
return audited