Chapter 08 · Data & Privacy

Data Protection & Privacy

The last of the seven defensive layers — layer 7: what the agent may see, what it may keep, and what it can be made to forget. The earlier layers stop an attacker from acting; this one governs the agent's relationship to data over time — per-tenant and per-user isolation, provenance, retention, and right-to-erasure. It is the difference between a system that can answer and a system you can put a customer's private knowledge into.

The two privacy boundaries

Memory makes an agent useful and dangerous in the same breath. The moment it remembers across sessions, two questions become security-critical: can one customer's knowledge leak into another's, and can one user read another user's private memory? The harness answers both with a single mechanism, but it is worth seeing them as two distinct lines.

Tenant ↔ tenant
The hard outer wall. One customer organisation's knowledge graph must never be visible to another's — not in retrieval, not in memory, not by accident. This is the boundary a multi-tenant SaaS lives or dies on.
User ↔ shared corpus
The softer inner wall, inside a single tenant. A user can see their tenant's shared corpus (documents and facts everyone in the tenant may use) plus their own private memory — but not another user's private memory. Net visibility: shared-in-tenant + mine, nothing else.

Both walls are enforced in the same place and by the same rule: a per-record check on every read and every write to the knowledge graph.

Per-record isolation: the visibility rule

The enforcement point is a decorator that wraps the knowledge-graph store (IKnowledgeGraphStore): src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/Scoping/TenantIsolatedGraphStore.cs. It sits between callers and the real backend, and on every operation it asks two questions about each record before letting the caller see it or touch it. The questions run through IKnowledgeScopeValidator (src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/Scoping/KnowledgeScopeValidator.cs), which checks tenant match plus dataset ownership.

The rule, stated plainly:

  • A node is visible only if its TenantId is null (a global record) or equals the caller's tenant; and
  • its OwnerId is null (the shared corpus) or the caller owns it.

Written as a truth table — both columns must land on a green cell for the record to be visible:

Record's TenantId Tenant check Record's OwnerId Owner check Visible to caller?
null (global) passes null (shared corpus) passes Yes
= caller's tenant passes null (shared corpus) passes Yes — tenant shared corpus
= caller's tenant passes = caller passes Yes — caller's own memory
= caller's tenant passes = another user fails No — another user's private memory
= another tenant fails (any) — No — cross-tenant, blocked outright

The net effect: a user sees their tenant's shared corpus plus their own memory — and nothing from other tenants or other users. The same check runs on writes, so a record can only be written into a scope the caller actually occupies.

!
Isolation is off by default, and says so

AppConfig:AI:Rag:GraphRag:MultiTenantIsolation defaults to false, which suits a single-tenant deployment. In that mode the decorator is not registered at all, and a host outside Development logs a warning at startup saying what is shared. With isolation off:

  • Still private: each user's remembered facts. Memory ids are namespaced by tenant and user (see memory namespacing), so recall, search and forget only ever reach the caller's own.
  • Shared by every user and tenant: the graph's entities extracted from ingested documents, and the learnings recalled into turns.
  • Shared either way: ingested documents through retrieval, and graph-based retrieval (GraphRAG). Turning isolation on does not make documents private.

If you run more than one customer on one harness, turn this switch on, treat it as a load-bearing setting, and verify it in every environment.

Ambient identity propagation

The visibility rule is only as good as the identity it checks against. The hard part is making the caller's identity available everywhere it's needed — including in background work that runs after the HTTP response has already been sent — without manually passing a user/tenant parameter through every method in the call chain. The harness solves this with an ambient mechanism.

AsyncLocal

A .NET mechanism that carries a value along an asynchronous call chain — including into background continuations spawned from it — without threading it through every method signature. Set it once at the top of a request and any code that runs as part of that request, however deep or however much later, can read it back. It is the right tool for "the current user" precisely because identity needs to follow the work, not the stack frame.

The accessor (src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/Scoping/KnowledgeScopeAccessor.cs) stores the user/tenant/dataset identity in a static AsyncLocal, set once at request entry. From there it flows automatically into child dependency-injection scopes and into post-turn background writes — so a memory written after the response still lands in the right tenant and owner, with no extra plumbing.

Identity is captured at the entry point, after authentication, by one thin adapter per transport — mounted on every HTTP host, not just the agent hub. A host that forgets to mount it does not fall back to something safe: unscoped records are stored as global, so every caller can read them.

Transport Capture point What it does
HTTP (Agent Hub) src/Content/Presentation/Presentation.Common/Scoping/KnowledgeScopeMiddleware.cs Runs immediately after authentication and before authorization; calls KnowledgeScopeInitializer to pull userId/tenantId from the authenticated ClaimsPrincipal and seed the accessor. An authenticated caller whose identity cannot be resolved is rejected with 401 rather than allowed to proceed unscoped.
HTTP (Bundle API) The same class, mounted in src/Content/Presentation/Presentation.ExecutionApi/Program.cs Identical behaviour and identical position in the pipeline, so plans and records created by an externally-triggered bundle run are scoped exactly as agent-hub turns are. This host previously mounted no scope adapter at all, which meant bundle-created records were written unscoped — that is, global.
SignalR src/Content/Presentation/Presentation.AgentHub/Hubs/KnowledgeScopeHubFilter.cs The hub-filter equivalent for real-time connections; same KnowledgeScopeInitializer, same claims source, so streaming turns are scoped identically to HTTP turns.
i
Identity comes from claims, never from the request body

Both adapters read the user and tenant from the authenticated ClaimsPrincipal — the identity the platform proved during login — not from anything the caller can set in the payload. A request cannot ask to be treated as a different tenant; it is whatever its token says it is.

Memory namespacing

Isolation by filtering is the primary control. Namespacing is the belt-and-braces backup: identity is baked into the memory node's id itself. Memory node ids follow the pattern:

memory:{tenant}:{user}:{key}

Because the tenant and user are part of the key, one user's memory key cannot collide with or address another's — even if the per-record isolation filter were somehow bypassed, there is no id a user could construct that names another user's memory without already knowing (and being) that user's scope. The id space itself is partitioned.

Enforced in all three local backends

Isolation that only holds for the in-memory development store would be a trap: it would pass every local test and then leak in production. The harness persists and filters OwnerId/TenantId in every local backend, so the same record-level boundary holds whichever store you deploy — this guarantee is local-storage-only; see the callout below for the remote-memory exception.

Backend File How isolation is persisted
In-memory (dev) src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/InMemory/InMemoryGraphStore.cs Preserves OwnerId/TenantId on merge.
Neo4j src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/Neo4j/Neo4jGraphStore.cs Persists owner_id/tenant_id; the Cypher uses coalesce so a write never null-clobbers an existing tenant.
PostgreSQL src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/PostgreSql/PostgreSqlGraphStore.cs owner_id/tenant_id columns on kg_nodes and kg_edges, with indexes; self-initializes its schema.
!
Remote memory hosting is not yet covered by this guarantee

When AppConfig:AI:RemoteMemory:Enabled is true, recall is answered by an external avatar-hosting service whose contract does not currently filter by caller identity — two users of the same harness deployment can see each other's remote-stored facts via content search. This harness's own write-gate still scans everything it writes before it leaves this process, but it cannot verify content already sitting in the remote store from some other source. Until the remote contract enforces per-caller filtering and echoes a trust signal on recall, treat one AvatarId as a single shared trust boundary and provision a separate deployment per isolation boundary you need — enforced at startup via RemoteMemoryConfig.AcknowledgeSharedRecallBoundary.

The harness side of the trust signal is ready: a recall result the remote service marks anything but trusted is never served, and a trust value it sends is carried on the result. Today's contract sends no trust field, so unmarked results are served by default. Once the remote service sends one on every result, set RemoteMemoryConfig.RequireRecallTrustSignal to true so an unmarked result is dropped instead.

Provenance: making every fact attributable

Isolation answers "who may see this." Provenance answers "where did this come from, and can I trust it." Every node and edge written to the graph is stamped — when GraphRagConfig.ProvenanceEnabled — by src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/Provenance/DefaultProvenanceStamper.cs, which produces an immutable src/Content/Domain/Domain.AI/KnowledgeGraph/Models/ProvenanceStamp.cs record carrying:

Field Meaning
SourcePipeline Which ingestion/processing pipeline created the record.
SourceTask The specific task within that pipeline.
Timestamp When it was written (UTC).
SourceDocumentId The originating document — or null if the fact was synthesized.
ExtractionConfidence How sure the extractor was (0–1) — or null.
LastModifiedBy The actor responsible for the most recent change.
Memory poisoning

An attack where a hostile party plants a false "fact" into the agent's memory during one session so that a later session retrieves it and is misled — the slow-burn cousin of prompt injection. Because the agent treats its own memory as trusted, a single poisoned record can quietly steer future answers. This is OWASP Agentic threat ASI06.

Provenance is the structural defence against it: every fact is attributable, so a downstream filter can act on memory whose SourcePipeline or SourceDocumentId is untrusted instead of blindly trusting whatever is in the graph. You cannot decide whether to trust a fact you cannot trace; the stamp is what makes the decision possible.

Trust-aware memory: the write-gate

The quarantine is not hypothetical — it is enforced on every write. KnowledgeMemoryService.RememberAsync runs an IMemoryWriteGate before anything is persisted. Content the gate judges untrusted is stored as MemoryTrust.Untrusted — quarantined rather than written as recallable — and the IsRecallable check is re-evaluated at read time, so a quarantined record never re-enters a prompt even if it slipped through. This directly closes the memory-poisoning (ASI06) path: a hostile fact planted in one session cannot silently steer a later one.

Compliance & retention

Knowing where data came from is half of governance; the other half is not keeping it longer than you're allowed to, and being able to prove what happened to it. A second decorator — src/Content/Infrastructure/Infrastructure.AI.KnowledgeGraph/Compliance/ComplianceAwareGraphStore.cs — handles the temporal and audit side:

  • On writes it stamps temporal metadata — creation time via TimeProvider.GetUtcNow() — and tenant metadata.
  • On reads it filters out expired nodes, so stale data simply isn't returned.
  • It emits a MemoryAuditEvent (Remember / Recall / Forget / Improve / Erasure / Expiry / DocumentRemoval, with ActorId, Timestamp and ScopeId) to IMemoryAuditSink. Retention expiry is recorded as Expiry and document removal as DocumentRemoval, both with the actor system. The default sink writes the event to the structured log (AppConfig:AI:Rag:GraphRag:AuditSinkProvider, default structured_logging), and only while ComplianceEnabled is on (the default); with it off, nothing is recorded. It is not one of the hash-chained JSONL governance trails. Deletions record how many nodes and edges were removed, never their ids: memory node ids embed the owner and the memory key, so a deletion record that listed them would keep what was deleted.

Retention rules are not hardcoded: they come from IRetentionPolicyProvider, resolved per entity type from AppConfig:AI:Rag:GraphRag:RetentionPolicies (ConfigRetentionPolicyProvider). A policy has no tenant or dataset, so every customer on one host shares the same lifetimes.

Retention periods outside the graph (#901)

GDPR's storage-limitation principle (Article 5(1)(e)) does not allow personal data to be kept with no end. Every store in the personal-data inventory declares how long it keeps what it holds, and a guard (EveryPersonalDataStoreIsDeclaredTests) fails the build if a store declares RetentionBasis.Unbounded without being on a list of known gaps that only shrinks (KeptForeverGaps). The stores with a period so far:

  • Conversations. A conversation with no new message for AppConfig:AI:Conversations:Retention:IdlePeriod (default 365 days) is deleted with everything found through it: its messages, observability sessions, spilled tool results, prompt-usage rows, token budget and call-once ledger rows. Reading a conversation does not reset the clock; writing to it does. ConversationExpiry deletes in the same stage order as erasure, under the conversation's turn lease, so a conversation with a turn running is never touched, and it asks only stores whose ErasureReach is NamedConversations, so the person's documents, plans, schedules and memories stay. Deleted bytes are cleared from the database files afterwards. A period under a day is refused at startup and by the sweep itself.
  • Prompt-usage records (when persisted) are deleted after AppConfig:AI:PromptUsage:Retention:RetainFor (default 90 days).
  • Plans. A plan nothing has happened to for AppConfig:AI:Planner:Retention:RetainFor (default 90 days) is deleted with its steps, outputs and execution log, whatever its state: finished, never run, or stopped waiting on an approval. Saving it, a step starting or finishing, and a log entry all count as activity. A plan a schedule runs, or a run is queued or parked on, is kept however long it waits: a quarterly schedule's gap is longer than the period. A plan deleted between being loaded and started is not run.
  • Delegation records. Each supervisor writes one file per UTC day, and a file nothing has written to for AppConfig:AI:Orchestration:Subagent:DelegationRetention:RetainFor (default 90 days) is deleted, so a record goes within the period plus a day. The sweep deletes only files it named, one folder below the storage path, and never follows a link, so a storage path set to a parent of the audit trails cannot reach them.
  • The chat response cache. Every cached model response expires after AppConfig:Cache:ChatResponseExpiry (default one hour, at most 30 days), in process memory and in Redis alike. Entries a Redis cache already holds from before this change have no expiry; flush the cache once after upgrading.
  • What the agent knows about a person. In the knowledge graph, what the agent remembered for someone (facts, preferences, skill-training experience), their work episodes and their episodic conversation segments are deleted once not written for AppConfig:AI:Rag:GraphRag:PersonalKnowledgeRetention (default two years). Every write stamps its time, so re-remembering a fact renews it; reads do not, because the graph does not record them. Knowledge extracted from documents, learnings and system records such as drift events are not affected. A period under a day is refused at startup and by the sweep. Cross-session memories go once not recalled or written for AppConfig:AI:Rag:CrossSessionMemory:Retention:RetainFor (default two years), from the cache and the graph database. A learning that decayed or that someone asked the agent to forget is hidden at once and removed for good after AppConfig:AI:Learnings:DeletedRetentionDays (default 30); a learning marked Permanent is kept by design. RetentionEnforcementService reads its interval live and removes at most 1,000 nodes a run, so the first run after an upgrade, which may find years of old personal knowledge, spreads the work over several runs.
  • Execution traces. A trace run (production or evaluation) that nothing has written to for AppConfig:MetaHarness:TraceRetention:RetainFor (default 30 days) is deleted. Traces hold prompts, model responses and tool payloads that cannot be found per person, so age is the only control on them and the period is kept short. A run's age is its newest file, so a run still being written is never touched and one a crash left unfinished still goes. A folder counts as a run only where the trace writer puts one, named by its run id and holding a manifest that names the same id, so a trace root pointed at a shared folder cannot reach other files. Only the files the writer creates are deleted, the manifest last so a delete interrupted by a locked file is finished by the next sweep, and links are never followed: an optimization's candidate definitions, or anything else placed in the folder, survive. The sweep runs inside a long-lived host (the first one six hours after start), so traces written by a short-lived process such as the evaluation runner are removed only by a host sharing its trace root.
  • The observability database. When enabled, a session with no activity for AppConfig:Observability:Retention:RetainFor (default 90 days) is deleted with its messages, tool executions, safety events and audit rows. Activity is the newest write to the session (starting, resuming, a turn's totals, ending) or row recorded under it, not its first start, which a resumed conversation keeps. Context snapshots and audit rows with no session go by their own age, so a conversation active for longer than the period loses its oldest snapshots. Conversation expiry and erasure remove a conversation's rows sooner; this catches what they cannot reach, such as sessions of conversations that were never stored. A conversation coming back after its session was removed starts a new one rather than writing to a row that is gone.
  • Log files. A run under AppConfig:Logging:LogsBasePath that nothing has written to for AppConfig:Logging:Retention:RetainFor (default 30 days) is deleted, except the run either file provider is writing. A run counts only when the marker the providers write at its root names it, because the logs folder is also one the file-system tool can write into; runs from before the marker existed are never swept, and a run another process is writing into the same folder is protected only by its age. Run ids and phases must each be one folder name; a sibling-folder name such as ../logsX used to pass the old check. Nothing in the shipped hosts starts a log run today.
  • Saved workflow state. A workflow nothing has saved for AppConfig:Infrastructure:StateManagement:Retention:RetainFor (default 90 days) loses its JSON checkpoint and its markdown rendering; anything else in its folder is kept. Status is not consulted, so a workflow paused at a human gate for longer than the period goes too; a deployment whose workflows pause that long sets a longer period. A folder counts only when its state file names that folder as its workflow, so a base path shared with other content cannot reach it, and a save that lands while the sweep is deleting keeps the workflow. Both files are now listed on the erasure receipt; before, neither was, because the store that writes them is built inside another.
  • Change-gate evidence. A blob nothing has stored for AppConfig:AI:Changes:EvidenceRetention:RetainFor (default 90 days, the period terminal proposals are kept) is deleted, unless an open proposal's gate decisions point at it, including a proposal quarantined because its seal failed, which is kept for investigation; storing the same content again renews it. If any open proposal cannot be read, the sweep deletes nothing. Only files named the way the store names a blob are matched, so the audit files kept beside the evidence are never reached.
  • An expired node no longer takes its source document with it. Retention removes expired graph nodes through IErasureOrchestrator.ExpireNodesAsync, which leaves the document content behind their chunk references. Before #901 it used erasure, which deleted the whole source document from both indexes when one node extracted from it aged, while it was still the source of every other node. Owner erasure still removes it.
  • Removing a document. IErasureOrchestrator.RemoveDocumentAsync takes one source document out of the corpus: its chunks from every vector and full-text collection (every page of the Azure AI Search index, which before stopped at the first thousand chunks), and what was extracted from it in the knowledge graph and the GraphRAG corpus graph. A node only that document produced is deleted; a node another document also produced keeps that document's references and survives; edges drawn from its text go; and in the corpus graph every community a changed node belongs to is deleted, because its summary was written from that text. An edge records only one source, so a relationship another document also asserts goes too, until that document is loaded again. A document id is derived from where the document came from, so this reaches every tenant and collection it was loaded into; it runs system-scoped, a store that cannot delete the chunks makes the result Partial, and every removal is audited. Operators run it through POST /api/compliance/document-removals with the document id in the body. It requires its own role, Harness.Compliance.RemoveDocument (the erasure role does not grant it, nor it erasure), and a sign-in from a tenant in AppConfig:AI:Erasure:OperatorTenantIds, the same trusted operators as erasure. It is refused while sign-in is bypassed, every request that reaches it is audited with the document id (refusals included), and it is rate limited to 30 requests an hour per operator. It is never an agent tool.
  • An optional age limit for loaded documents, off by default. A loaded document is the organisation's own business content, so by default it is kept until someone removes it. An organisation whose policy limits how long such content may be held sets AppConfig:AI:Rag:Documents:Retention:Enabled; each document not loaded for RetainFor (default three years) is then removed by the same audited removal an operator runs, recorded with retention as the actor. Loading a document again restarts its clock. The time of each load is kept in its own small database (AppConfig:AI:Rag:Documents:LoadLedgerDatabasePath, default data/documents.db), holding a document id and a time only, written before the document reaches any store; a load that cannot be recorded fails the ingest and leaves any copy an earlier load indexed untouched. (Before, any failure ahead of the store writes, such as an embedding error, also deleted that earlier copy; clean-up now runs only once this load's own writes have started.) A removal forgets the record only up to the load it judged, so a document loaded again meanwhile keeps its new time. A removal that ends Partial keeps the record and is tried again on the next sweep; at most 200 documents go per sweep, oldest first. A retry is written to the compliance trail only when it ends differently from the last recorded attempt (completed, other stores failing, a different failure, or anything removed), as a pair naming the first attempt under retry_of, so the trail grows with requests rather than with sweeps (#998). A retry that dies part-way leaves the first attempt and last outcome, both still true; after a restart the first retry of each document is recorded once more.
  • The load record is one process's file, so the age limit refuses shared stores. A removal deletes from every tenant and collection of the document stores, but the record lives under one host's folder. Where another process can write the same stores (Azure AI Search, a Postgres or Neo4j graph, another host beside this one), that host's recent load would be missing here and the document deleted for everyone. The host therefore refuses to start with the limit on unless every store is in-process (the FAISS index with the in-memory graph), a shared IDocumentLoadLedger is registered, or the deployment sets AppConfig:AI:Rag:Documents:LoadLedgerSharedByEveryWriter because every writer uses the same file on one machine; the sweep re-checks this every run. This is the same single-instance rule the architecture guide states for the other SQLite stores. Limits that remain: documents loaded before this release, or whose record was lost with a cleared base folder, have no load time and are never reached (remove them by id, or load them again); a document whose id a custom chunker formed in another shape cannot be removed by id at all, so it is not recorded and a warning is logged; and a load that lands after a removal has started but before its chunks are deleted loses that copy while keeping its record, so it should be loaded again.
  • Kept by design, with the reason in the inventory: schedules (the owner's standing instruction, identifiers only, kept until they delete it or are erased) and the call-once ledger's workflow-run rows (a run id and tool name, nothing that names a person; deleting one would re-arm a call-once tool). A conversation's ledger rows go with the conversation.
  • Loaded documents, and the knowledge drawn from them, are kept by design. They are the organisation's own business content, so the Azure AI Search indexes, the GraphRAG corpus graph and the document-derived nodes of the Postgres and Neo4j knowledge graphs keep them until the organisation removes the document, or until the optional age limit above does. Each store's entry in the inventory says so, and says what does age out beside it (personal knowledge, two years). A person's erasure still removes everything they loaded, by owner; documents other people loaded may mention them, and the erasure receipt now tells them so (below).
  • Spilled tool results (7 days), resolved escalations and terminal change proposals (90 days), orphaned token budgets (30 days) and the knowledge-graph entity types listed above already had periods.

Every store in the inventory now has a retention period or a written reason to be kept. The guard that enforced this one store at a time keeps an empty list of exceptions (src/Content/Tests/Presentation.Common.Tests/Architecture/KeptForeverGaps.cs), so a new store that keeps data with neither fails the build.

What the audit trails record about people

Because nothing in a hash-chained trail can be erased, the trails record as little about people as still answers their questions (#903). Across the trails:

  • People — approvers, the person who cancelled an escalation, a change reviewer, the caller behind a drift push or recalculation, the caller behind a direct tool invocation, and the operator behind an erasure, a data export or a document removal — are recorded as a keyed reference, ref:{key id}:{HMAC}, never by name or user id. Whoever holds the key can compute a named person's reference and find every approval they gave; nobody without it can reverse a reference or confirm a guess. This keeps the trail's purpose, recording who approved or denied each governed action, without keeping the identity in clear.
  • Tool arguments keep their names; each value is recorded as a keyed fingerprint, fp:{key id}:{HMAC}, so the key holder can confirm a value was the one sent without the trail holding it.
  • Free text — an escalation's description, an approver's reason and instructions, a reviewer's reason, the governance trail's action and decision text — is kept, because the reasoning is the accountability record, with every redaction category applied. A value the record pseudonymizes elsewhere is replaced by its reference wherever the text repeats it. Redaction finds identifiers by their shape (an email address, a phone number, a card, an IBAN, a national id); a plain name typed into a reason has no shape to find and is kept as written. Ask approvers to give reasons, not names.
  • Outbound requests keep their scheme, host and port, which is what the egress trail exists to answer, and a keyed fingerprint of the full address: a path or query often names a person (/users/octocat, ?email=…).

The key is AppConfig:AI:Audit:PseudonymKey. Set it from a secret store wherever more than one instance writes the trails. Without one, a key file is made once at .agent-sessions/keys/audit-pseudonym.key with access for the application's own account only, and read on every later start, so references stay the same across restarts. FoundryHost puts it at $HOME/agent-state/keys/audit-pseudonym.key, beside the trails it roots there, because Foundry keeps only $HOME across idle and resume (#996). Startup refuses a key file inside any audit folder or the archive, so the key never travels with the records it protects, and warns at startup when an existing key file is readable by other accounts. Back the key up: without it, references can no longer be recomputed. If the key file is lost while the trails survive, the next start makes a new key and logs an error: restore the earlier key rather than carry on, or new references will not match the ones already recorded. Each reference names its key, so after a rotation old references read as made under an earlier key rather than as references that match nobody.

The escalation state store still holds the full values while an escalation needs them, under its own retention. Records written before this change hold raw values and cannot be rewritten; they are kept on the same Article 17(3) basis as the rest of the archive, below, and leave it when the archive's retention period ends. The endpoints that serve audit records (the compliance report, the drift audit list) return them as stored, raw or not: each requires an explicit role, they are the evidence that role exists to read, and rewriting old records on the way out would show auditors a trail that differs from the one the chain verifies.

The audit archive: why erasure does not reach it, and how long to keep it

The audit trails (governance, escalation, change, egress, drift and compliance) are hash-chained, and the audit archiver moves their finished days into write-once storage (Presentation.AuditArchiver, #416). Removing one person's records from them would break the evidence they exist to provide, so erasure lists the six live trails on the receipt rather than editing them. The archive itself is built only in the separate archiver host, so it gets no receipt line of its own. The basis is GDPR Article 17(3): the right to erasure does not apply where processing is necessary for compliance with a legal obligation (point (b)), or for the establishment, exercise or defence of legal claims (point (e)). That basis does not remove storage limitation (Article 5(1)(e)): the archive needs an end date too, set by the deploying organisation.

  • Where the period lives. In the storage, not in the application: the archive's Azure Blob container carries a locked time-based retention policy, and a lifecycle management rule deletes day-files once that period has passed. The application never deletes from the archive; it mounts it read-only.
  • Recommended periods. Pick the longest obligation that applies and set both the lock and the deletion rule to it. As reference points: the EU AI Act requires providers and deployers of high-risk AI systems to keep the logs those systems generate for at least six months (Articles 19 and 26(6)); PCI DSS 4.0 requires twelve months of audit log history, the last three immediately available (requirement 10.5.1); sector rules (financial services, health) can require years. Where nothing longer applies, twelve months covers both of the first two. Agree the period with your data protection officer; the template cannot know it.
  • What the deletion rule must leave. Delete only the day-files ({log}/{yyyy-MM-dd}.jsonl). Keep the archive's marker file (.audit-archive), each log's witnesses/ and accepted/ folders: they hold sequence numbers, hashes and operator decisions, not the records, and verification depends on them. Verification starts at the oldest day-file that remains and logs that earlier records expired, so deleting old days does not break it (pinned by AuditArchiverTests.Verify_AfterTheOldestArchivedDayExpires_StillPasses_WithItsWitnessesAndMarkerKept).
  • Live day-files. The archiver deletes each live copy once its archived copy is safely written, so the live folder holds only days not yet archived. Without the archiver, live audit files are never deleted; running it is how they get a retention period.
  • What the trails hold about people is reduced to pseudonymous references (#903); see what the audit trails record about people.

The erasure receipt reads each unsearchable store's live period: a store whose retention is running is listed as RetainedUntilExpiry with "each record is deleted within N", and one switched off is listed as kept indefinitely, which makes the receipt Partial.

i
Time is injected, not read from the wall clock

Creation and expiry are computed from TimeProvider.GetUtcNow(), an injected clock, rather than DateTime.UtcNow. That keeps retention behaviour deterministic and testable — you can fast-forward a fake clock in a test to prove expired nodes really do drop out of reads.

Right-to-erasure (GDPR Article 17)

"Delete the user's data" is easy to say and hard to do correctly, because an agent's knowledge of a user is scattered across several stores, and some of them cannot be searched for one person at all. The harness erases everything it can find for the person and lists everything it cannot. The receipt's verdict says whether anything is kept with no end date. Full does not mean "fully gone": logs, traces and the response cache can still hold the person's text until they expire, and the audit trails and business content are kept on purpose (see the receipt).

PersonalDataErasureCoordinator (src/Content/Application/Application.AI.Common/Services/Compliance/) runs the request. It reads the person's conversation ids first, and the ids their planned tasks ran under, which the plan store records against the person each time a plan starts (#906). It then erases the knowledge graph (nodes, edges, feedback weights, the vector and full-text content of linked documents, and cross-session memory) through DefaultErasureOrchestrator, then every store registered as an IPersonalDataEraser: the document indexes by owner, schedules, the person's finished workflow, evaluation and bundle run records, the bundles they staged, and, through the conversations and the planned tasks' model steps and runs, tool-result spill files, prompt-usage records, token budgets, the call-once ledger and the observability database. The conversations and the plans go next, and the token budgets and call-once ledger last, for whichever of the two was actually erased. A store reached only through a conversation or a plan is erased before it, so a failure part-way leaves something a retry can still find. A planned task run while the request runs is kept, and the receipt says to run erasure again. It runs system-scoped, so the tenant-isolated graph does not hide the person's data from an operator acting on their behalf.

Most of the stores reached through a conversation id record no owner, so erasing a conversation erases whatever they hold under its id. Every id a planned task derives contains : ({run}:{step}, planrun:{run}), and the conversation stores refuse to create a conversation whose id does (#907); the AgentHub hub and the bundle API answer with the reason. Without that, a person could name a conversation after someone else's planned-task step and have its records erased with their own. A conversation created with such an id before the rule still opens and is still erased, but erasure does not follow its id into the stores without an owner, and the receipt says so. The rule closes shapes, not knowledge: a person who learns another's randomly generated job id could still name a conversation after it.

The conversation ids are read through each store's id-only erasure listing (IConversationIdSource, #907). It loads no transcripts, and it never skips a record it cannot read: a stored conversation that cannot be read is left untouched, along with what it leads to, and the receipt gets a failed "could not be read" line. The same applies to a file whose contents name a different conversation than its file name. Failures on the erasure path are logged through MessageWithheldException, which keeps each exception's type, stack and inner chain but not its message. A store's message can name the person being erased, through a file path or an echoed owner filter, and the pattern-based log redaction does not catch ids.

A request that fails after the conversations or plans are deleted can still be retried (#907). Before deleting any of them, the coordinator records the ids it read in the erasure journal (IErasureJournal, a small SQLite database). Every later request for the same person merges those ids in, and a request clears only its own entries, once every store has erased or cannot erase at all. If the journal cannot be written, no conversation or plan is deleted and the receipt says so. Withheld conversation ids stay in the journal until its retention runs out (AppConfig:AI:Erasure:JournalRetention, a year by default, never under 90 days), so later receipts keep saying their records were kept. The same retention removes anything left by a request that was never retried. The journal holds people's ids, so it is in the personal data inventory, and clearing it also clears its write-ahead log.

While the journal holds an erased conversation's id, nobody else can create a conversation under it. They are refused exactly as for another person's conversation, because the retry would otherwise erase their records filed under the same id. The erased person may reuse their own id. One erasure request per person runs at a time, so overlapping requests cannot clear an id between another's read and record. Both reach only the hosts that share the journal. The shipped conversation stores and journal are single-host, so a deployment that shares a conversation store across hosts needs a shared IErasureJournal too. A held id reads as not found but cannot be created, so someone who can guess an erased conversation's id can tell that an erasure is unfinished.

Before reading anything, a request stops the person's planned tasks that are still running (IPlannedTaskCanceller, #907). Otherwise a task would keep writing under the ids erasure reads and clears. It cancels only runs of plans the person owns, so it never stops someone else's task, because only a plan's owner can run it. It then waits up to 30 seconds for them to end. It reaches only runs on the same host. A run that does not stop in time, or runs elsewhere, keeps its plan as before, and the receipt says to run erasure again. The person's own run of a shared plan is deliberately left running, because stopping it would stop everyone's runs of that plan. It falls back to the same "run erasure again" line.

Workflow and evaluation run records (InMemoryRunJobStore, #926) are held in process memory only, and each names the person who started the run, their tenant, the target and the capability envelope it runs under. A finished run is dropped AppConfig:AI:WorkflowSubmission:RunRecordTtl (an hour) after it ends. Erasure removes the person's finished runs in every tenant at once, and releases what else is kept under their ids (progress bookkeeping, an evaluation's report). Those are released first, and if one cannot be, the records are kept so a retry can still reach it. The store removes only finished runs: removing a running run's record would let a second run start on the same workflow while the first is still executing, and removing a parked one would strand the approvals it waits on. So before anything is read, erasure (#992) ends the person's live runs through the same cancel path an owner uses: a queued run is cancelled and never starts, a parked one is cancelled and its pending approvals are withdrawn (attributed to system:personal-data-erasure, not to the person), and an executing workflow is signalled to stop. Alongside the planned-task stop above, erasure then waits up to 30 seconds for runs still executing, cancelling any that parked or were queued meanwhile and signalling any that started; an executing evaluation cannot be signalled, so it is only waited for. The run store then removes the cancelled runs with the finished ones, in the same request. Once every store has run, the coordinator counts every record still held for the person, so a run that ended meanwhile is counted too. When any is (a run still executing after the wait, or one started meanwhile), the receipt gets a Skipped line, "workflow and evaluation runs still held", and is Partial, telling the person to run erasure again once it has ended. The store is single-host, like the run substrate it belongs to.

The bundle API keeps two more stores in process memory (#990). Its run records (InMemoryBundleRunJobStore) name the caller and hold the conversation id, the messages they sent and the agent's final answer, until BundleExecution:RunRecordTtl (30 minutes) after the run ends. Its staged-bundle handles (InMemoryBundleHandleStore) name who staged each bundle, until BundleExecution:HandleTtl (30 minutes) after the bundle was last used. Erasure removes the person's finished bundle runs, and keeps one still queued or running, as for workflow runs. It removes every bundle they staged and deletes its staging folder, except one a run is still reading, which goes when that run ends. A queued bundle run whose bundle was removed fails when it would have started, so it does not run after the person is erased. Each store's kept records get a Skipped line of their own, "bundle runs still held" or "staged bundles still held", and the receipt is Partial. Both are erased and copied only by a request served by the same process as the bundle API. The bundle API runs in Presentation.ExecutionApi, which serves erasure and export for its own stores (#1003), so send the request there as well as to AgentHub (each request covers the host it is sent to).

Replacing a run store. Each run store's "still held" count is registered with AddSingleton<IKeptRunSource>, not TryAdd, and forwards to the store's own service (IRunJobStore, IBundleRunJobStore, IBundleHandleStore). If you wrap one in a decorator, register the decorator in place of the store as that service, so the shipped registration reaches it. Do not add another IKeptRunSource for it, or every receipt shows two kept lines for the one store.

Ingested documents record their owner exactly as the identity provider issued it, and their erasers match that form. A scheduled run writes under its schedule's owner, so a schedule keeps the owner as issued as well as lower-cased, and each fired run carries the issued form (#907). A schedule created before that runs under the lower-cased form until its owner next lists, reads, pauses or resumes their schedules, which fills the issued form in. Documents such a run ingested for a person whose id is not already lower-case are out of reach of erasure. Microsoft Entra object ids are always lower-case, so this only affects other identity providers.

Two ways in, both producing the same receipt:

  • Self-service: POST /api/compliance/erase-my-data erases the signed-in caller, and only them. There is no field through which another person can be named.
  • Operator: POST /api/compliance/erasures with the person's id in the body, for someone who cannot sign in. It requires the Harness.Compliance.EraseSubject role and a sign-in from a tenant listed in AppConfig:AI:Erasure:OperatorTenantIds; with that list empty (the default), operator erasure is off. The role alone is not enough, because each organisation's administrator assigns roles in their own tenant and erasure reaches every tenant. Every refusal is audited, and the endpoint is rate limited.

Both are refused while sign-in is bypassed, because every caller is then the same synthetic person. Self-service erasure is also refused for an application's own token (#907): every caller of that application shares its identity, so "erase my data" would erase all of theirs (ClaimsPrincipalExtensions.IsApplicationOnly).

  • Any issuer: a token is an application's when it carries idtyp=app, when its subject is the calling client's own id (RFC 9068's client-credentials shape; Okta names the client in cid), or when it carries Auth0's gty=client-credentials. Other providers' service accounts, such as Keycloak's, are not recognised; a host using one should turn on an explicit marker.
  • Entra workforce and External ID tokens only: a token is also an application's when it has no scp, which Entra emits only for people, or when its oid equals its sub, which is Microsoft's documented check.
  • Not applied elsewhere: other providers often give a person no scp, and Azure AD B2C makes oid equal sub for every person, so refusing on those would deny people their own erasure.

The refusal is recorded as an erasure audit record (see below for where that is kept). Operator erasure still accepts an application holding the erasure role, since an automated pipeline for data-subject requests is a legitimate caller there.

Each request covers the host it is sent to (#1003)

Erasure, document removal and export run inside one process and reach that process's stores only. Hosts never call one another. Most stores live inside their process: the workflow and evaluation run records in memory, and, by default, the conversation database, journal and plan database as files beside each host's own binaries. The document indexes are wherever the host's configuration puts them: the in-process FAISS index and SQLite full-text table, the default for a host that sets nothing, or an Azure AI Search index. Choosing Azure AI Search (AppConfig:AI:Rag:VectorStore:Provider = azure_ai_search) without its Endpoint, or setting an Endpoint without choosing it, stops the host at startup (#1012). Either half alone would erase the person from a store that holds nothing while their chunks stayed in the real index, and the receipt would read Full; an endpoint lost to a failed Key Vault reference or an environment override is the usual cause. A request sent to AgentHub therefore leaves the Execution API's copy of the same person's data alone, and the reverse. So every receipt and every copy names the host it covers in a host field, the host's application name such as Presentation.AgentHub or Presentation.ExecutionApi. Every audit record names it too. Full and isComplete speak for that host alone.

A deployment must send each request to every host that holds personal data, and a person is erased everywhere only when every one of those hosts has returned a Full receipt. Both hosts that serve the compliance API serve it at the same paths, with the same roles, operator tenants (each host reads its own AppConfig:AI:Erasure:OperatorTenantIds), refusals and rate limits, because both mount the one implementation in Presentation.Common.Compliance. The rate limits and the two-copies-at-once export limit are per host. Where two hosts are pointed at one shared durable store, such as a shared conversation database, whichever host is asked first erases that store for both. Their in-memory stores still need a request each. A host scaled out to several instances keeps its in-memory stores per instance, and a request reaches only the instance that serves it. The shipped run and bundle stores are single-instance by design.

The shipped hosts, and whether they hold personal data:

  • AgentHub holds conversations, memories and the knowledge graph, plans, schedules, documents people load, and the rest of the stores on this page. It serves the compliance API.
  • Execution API holds workflow, evaluation and bundle run records, and the conversations its agents write when a run names one. It also holds the plans its workflows persist and whatever its agents' tools store. It serves the compliance API at /api/compliance/*, authenticated with its own audience. Its anonymous development mode makes every caller one person, so the API refuses self-service and operator requests there, as AgentHub does under its sign-in bypass. Its receipt lists the bundle runs and staged bundles it keeps in memory (#990).
  • FoundryHost keeps each Foundry session's state in that session's own $HOME. It serves no erasure or export endpoint. You erase and export its data through Foundry's session API instead (see below).
  • ConsoleUI and EvalRunner are run by hand, not deployed as services. They compose the same stores, so anything they write lands in their own working directory. They serve no endpoint, so clear their state directly. AuditArchiver only moves existing audit day-files into the archive, and LoggerUI only prints log pipes. Neither writes personal data of its own.

Erasing and exporting FoundryHost's data: delete or copy the Foundry session

FoundryHost cannot serve these endpoints, and it does not need to. Callers reach a hosted agent only through its Foundry endpoint. The documented routes are the protocols (.../endpoint/protocols/openai/responses, .../endpoint/protocols/invocations) and the sessions API (Microsoft Learn, Manage hosted agent sessions). The container serves POST /responses or POST /invocations and GET /readiness (Hosted agent runtime contract). Neither page documents a route to any other container path, so we infer that /api/compliance/* would not be reachable. Every call also lands in one session's sandbox. A session is "a stateful, isolated sandbox tied to a single logical workload (for example, one user's chat)", with its own persistent $HOME (Manage hosted agent sessions). FoundryHost keeps what it writes in that $HOME, with two exceptions, both off by default. Durable governance state stays in the application directory, on the sandbox's ephemeral root disk. Prompt usage goes wherever its connection string points (src/Content/Presentation/Presentation.FoundryHost/README.md). The rest is:

  • the agent session store, under $HOME/.checkpoints;
  • the planner, conversation, document-ledger, schedule and erasure-journal databases;
  • workflow state, execution traces, offloaded tool results, and subagent delegations and mailbox;
  • the embedded Kuzu graph, file logs and the audit trails, all under $HOME/agent-state.

An erasure run inside the container could reach only the one session the request landed in. Deleting the session reaches all of it.

  • Find the person's sessions. Each session belongs to one isolation key.
    • With the default Entra isolation source, the key is the caller's Microsoft Entra identity, and the list call returns only the caller's own sessions.
    • With the header source, the key is whatever your application sent in x-ms-user-isolation-key.
    An operator who holds the Foundry User role on the project sees and deletes every session on the agent. Listing is GET .../agents/{agent}/endpoint/sessions. If your application calls the agent on people's behalf under its own identity, it must record which sessions are whose: FoundryHost cannot tell you.
  • Erase. DELETE .../agents/{agent}/endpoint/sessions/{id}, sent with the session's isolation key, "terminates the sandbox and releases its resources". The platform otherwise "retains $HOME state for 30 days unless you delete the session" (Customer-managed keys in Microsoft Foundry), so deleting the session is what removes the $HOME above. A session nobody deletes goes after 30 days of inactivity.
  • Export. The session files API lists and downloads what is under $HOME: GET .../sessions/{id}/files?path=... and GET .../sessions/{id}/files/content?path=.... Copy agent-state and .checkpoints. They are the host's own storage formats (SQLite, JSONL, framework session files), not the JSON copy the other hosts return.

Only when a session is one person's. Deleting or copying a session is a per-person erasure or copy only if nobody else's data is in it. That holds for the default Entra isolation source, where each caller has their own sessions. It does not hold in two cases. The first is a header isolation key shared by several people, such as a tenant id. The second is several users multiplexed into one session (Microsoft Learn, Multiplex multiple users in one hosted agent session). FoundryHost does not separate users inside a session. In those deployments, copying a session hands the requester the other people's data, and deleting it erases theirs too. Use one isolation key per person if you need either right per person.

What deleting a session does not cover.

  • The conversation history Foundry itself stores for the Responses protocol is kept apart from the session. Delete it through Foundry's conversations API.
  • The session's audit trails, including the compliance trail, are inside $HOME. Deleting the session deletes them too, so the proof they hold goes with it. A deployment that must keep that proof archives the trails first (see the audit archive).
  • A store promoted to an external service is shared by every session: an external knowledge graph (GRAPH_PROVIDER, or AppConfig:AI:Rag:GraphRag:GraphProvider), a graph database other than the embedded Kuzu, any document index other than the in-process FAISS one (Azure AI Search through AZURE_SEARCH_ENDPOINT, say), Redis (REDIS_ENDPOINT), or the observability database (AppConfig:Observability:PostgresConnectionString). Deleting a session leaves what it put there. Which of them can still be erased per person depends on whether they record an owner (see below). FoundryHost names each one at startup (FoundryHostErasure).
  • Telemetry that has left the container: the Foundry hosting layer's traces and logs, and the harness's own Azure Monitor or OTLP export, sit in the Application Insights resource or collector they were sent to, under its own retention (see telemetry export for turning that off).

The shared stores: owned by the caller Foundry verified (#1008)

FoundryHost declares the Responses protocol at container protocol 2.0.0. That is the only version the Agent Framework hosting package it ships with speaks, and Foundry no longer serves 1.0.0 (Migrate hosted agents to the latest version). On 2.0.0 the platform puts the caller's per-user id in an x-agent-user-id header on every protocol request. It generates the header from verified identity, and its gateway drops every caller header outside a short allowlist, so a caller cannot send their own (Hosted agent runtime contract). FoundryHost runs each request as that user: it builds the request's principal from the header (FoundryCallerIdentity), and the same knowledge-scope middleware every web host mounts sets the scope from it (FoundryRequestScope). The id resolves through ClaimsPrincipalExtensions.GetUserIdOrNull(), like every other host's caller.

  • The header is trusted only behind Foundry. If the container's port is ever reachable without passing through Foundry, anyone can send the header and be taken for anyone. Never publish port 8088.
  • No header, off the platform: a local run. The request runs unscoped, as every request did before #1008, and what it writes carries no owner.
  • No header, in Foundry (FOUNDRY_HOSTING_ENVIRONMENT set). A /responses request without it is refused with 401. The platform stamps every protocol request, and its gateway authenticated the caller, so a missing id is a caller we cannot name, not an anonymous one. The readiness probe never carries it and is served as before.
  • A header that names no one usable: sent twice with different values, blank (even beside a real value), or an id an operator erasure would refuse to name (longer than 256 characters, or with surrounding whitespace). The request is refused with 401 instead of being run unowned, because a record with no owner reads as global. The same value sent twice is one caller.
  • Nothing else establishes the caller. A bearer token, an x-client-* header, or a principal set earlier in the pipeline is ignored.

What that owner reaches, store by store:

  • Knowledge graph store (Neo4j or PostgreSQL). Memories and learnings written during a request record that caller as owner, so owner erasure and export find them. That includes what the request leaves running after it answers, which keeps the caller's scope. Two kinds of record carry no owner: entities derived from ingested documents, and what work no request started writes, such as a scheduled job. This needs AppConfig:AI:Rag:GraphRag:ComplianceEnabled (on by default): without it, edges are written with no owner, and FoundryHost warns about the store instead. The graph compares owners ignoring case. That is safe for the GUID and e-mail ids it was written for; Foundry documents its id only as opaque, so two ids differing only in case would be one owner there.
  • Document index (Azure AI Search). A document ingested during a request is stamped with that caller. Owner erasure deletes its chunks, and export copies them. The index is still kept by design as business content, as for every other host.
  • A provider the template does not ship: a graph database other than Kuzu (Kuzu is the only backend shipped), or a knowledge graph or document index added by you. Not promised. FoundryHost cannot tell whether it writes an owner, so it warns about it at startup. Check your provider stamps the knowledge scope's owner before relying on per-person erasure there.
  • Observability database. Not reached. Its rows name only a conversation, and the record of whose conversation it was stays inside the session. FoundryHost still warns about it at startup. Keep personal data out of it, or clear it as a whole.
  • Redis. Not reached. Its entries are keyed by a hash of the model request and go only when they expire (at most Cache:ChatResponseExpiry). FoundryHost still warns about it at startup.

Erasing one person from those stores. FoundryHost still serves no erasure endpoint (see above). Send the request to a host that serves the compliance API and is bound to the same store: POST /api/compliance/erasures, or /exports, naming the person by their Foundry user id. Whichever host is asked first erases a shared store for both (each request covers the host it is sent to). Two limits apply:

  • You need the person's Foundry user id. Foundry documents it only as opaque. It is not documented to equal their Microsoft Entra object id, so it may not match the id the same person has on your other hosts. Foundry's documentation gives no way to look it up for a given person, and FoundryHost does not log it. Until one exists, a per-person request against these stores works only where you already know the id. Otherwise clear the stores as a whole.
  • Records with no owner stay. Those written by a request without the header, by work no request started, or derived from documents are not found by any per-person request.
  • Two hosting options would break this. The Foundry hosting layer's ResilientBackground re-runs a recovered turn with no request behind it, so with no owner. SteerableConversations runs a second caller's input inside the first caller's running turn, so as the first caller. FoundryHost turns on neither, and a test keeps it that way. Before turning on either, re-establish the owner from the turn's persisted platform context.
  • An application calling as itself is one owner. The id is the caller Foundry resolved. If your application calls the agent under its own identity without naming the person it acts for (the x-ms-user-identity delegation in Multiplex multiple users in one hosted agent session), we expect Foundry to give every person it relays the application's id. Microsoft does not document this, and we have not checked it on a deployment. If so, they share one owner, so an erasure naming it erases all of them. FoundryHost cannot tell such a caller from a person, as the other hosts do for an application's own token. Delegate the person's identity if you need either right per person.
✓
The receipt says what happened in every store

An ErasureReceipt (src/Content/Domain/Domain.AI/KnowledgeGraph/Models/ErasureReceipt.cs) is a structured record returned to the caller. It carries:

  • RequestId and ScopeId (the person's id, lower-cased and trimmed; returned to the caller and never logged), and the RequestedAt / CompletedAt window.
  • Host: the host whose stores the receipt covers (see each request covers the host it is sent to).
  • UnmatchedDocumentIds: document ids drawn from the erased graph nodes that matched no row in any store.
  • The knowledge graph's counts: nodes, edges, feedback weights, vector embeddings, full-text rows and cross-session memories actually removed.
  • Stores: one line per store, with a status and, unless it was erased, a fixed reason. Erased (with the count removed), Failed, Skipped (held back: an earlier store failed, or the person's conversations or planned tasks started or ran while the erasure was under way, or one of their workflow, evaluation or bundle runs had not ended, or a run was still using a bundle they staged, or a store was only partly erased), NotSupported (a store configured in this host that holds personal data but cannot erase one person's), and three for stores that cannot be searched for one person: RetainedUntilExpiry (each record is deleted within a period: log files, traces and the response cache by default, and stores held only in memory), RetainedIndefinitely (nothing ages it out: one of those stores with its retention switched off, or durable escalation state and durable change proposals, whose closed records are kept only until a period that can be switched off) and RetainedByObligation (the tamper-evident audit trails, kept on purpose; the line names the kinds of data each holds, for example tool inputs or the network addresses a tool reached). One more line is always there: RetainedAsBusinessContent, "documents other people loaded", telling the person that documents others loaded, and what was drawn from them, may mention them and are kept as the organisation's business content until it removes them; with the document age limit running, it adds how long.
  • Completeness and CompletenessReason. Full means every store that can find the person erased them and no store the host runs can still hold their data with no end date, other than the audit trails and the organisation's business content, which are listed with what they hold rather than counted. Any failed, held-back or unsupported store, or any store retained indefinitely, makes it Partial and names it. An earlier version of this page said that the stores on the retention gap list made every default receipt Partial; they could not, because each of them erases by owner and so appeared as an erasure line. They are now kept by design, with the reason above. Turning on durable escalation state or durable change proposals (EscalationsEnabled, ChangeProposalsEnabled, both off by default) makes every receipt Partial, because those stores keep open records with no end date.

What erasure cannot reach

Every store declares what it can do with [PersonalDataStore], and the receipt reports from those declarations. The stores that cannot erase one person's data, by default:

Why not Stores
Not keyed by person, so one person's records cannot be found The chat response cache, the log files and structured application logs, execution traces, agent delegation records, change proposals and their evidence, durable escalation state, and the in-memory learnings store
Kept on purpose: removing a person would break tamper-evident evidence The governance, change, drift, egress, escalation and compliance audit trails, and the audit archive
Erasure's own record of unfinished work The erasure journal, which ages out after JournalRetention
Deleted item by item, not by person Workflow checkpoints and their Markdown copies
  • A store a deployer adds that declares [PersonalDataStore] but has no eraser is listed as NotSupported ("the store configured in this host holds personal data but cannot erase one person's"), and the receipt is Partial.
  • A cross-session memory backend that cannot delete (a remote one) makes the receipt Partial, with the reason "cross-session memory purge is not supported by the configured backend".
  • In memory, outside the inventory guard's sight until #990. The guard found a store by the storage call it makes, and a store held only in memory makes none, so the bundle API's two stores were missed. It now also fails the build for any type that keeps a collection of records with an OwnerId or UserId field and is not declared. It still cannot see a store whose records carry no owner, such as one keyed only by a run or conversation id. Those are declared by hand. Two types it flags are listed as exceptions, each with its reason: a per-request buffer of graph nodes, and the AgentHub's record of open connections, which is dropped when a connection closes or has been idle for the configured time (five minutes by default). One type it cannot see is listed by hand: the workflow progress feed, keyed by run id, which buffers events only for an open watcher and never a step's output (#1005). Both exceptions whose reason rests on what their records carry are pinned to every field of those records and to every type that calls them directly, so a field or a direct caller added later fails the build until someone re-reads it. Text that reaches those callers from further up (cancellation notices, a run's caller-safe failure message) is not pinned; the exemption names the contracts it relies on instead.
  • Some stores have no receipt line at all: the erasure journal, the in-memory learnings store, and the audit archive. The erasure, export and document-removal records are on it, as the compliance audit trail.
  • Self-service erasure is limited to 5 requests an hour per person; operator erasure to 30 an hour.
  • Spilled tool results written before #928. The conversation database compares ids exactly, so ticket-42 and TICKET-42 can belong to two people. (The file-backed conversation store, on Windows or macOS, treats the two as one conversation: it refuses the second when another person owns the first, and lets the same person use both names for one transcript.) Spill folders are now named after the id lower-cased plus a hash of the exact id, so two such ids never share a folder, even on Windows or macOS, which ignore case in names. Before #928 the folder kept the id's case, and on those systems both ids wrote into one folder. Erasure and the person's copy still find such an old folder, but only for the id that created it: it is erased and copied whole for that id, including any spills the other id wrote there, and the other id's spills in it are not found for that other person. The files carry no owner, so they cannot be separated. Old folders receive no new writes and are deleted by the 7-day spill retention. A page of an old spill can no longer be fetched by the agent.

The erasure audit record

Each request writes an Attempted record before anything is deleted and an outcome after, paired by a correlation id, with the action right_to_erasure. The record is meant to prove the erasure happened without keeping the identity it erased: it holds who asked (an operator by a keyed reference in the compliance trail and by id in the log line; a person erasing themselves only as data-subject), the host that handled it (host, #1003; export and document-removal records carry it too), per-store counts, the receipt's request id, and a pseudonymous subject reference. The reference is an HMAC-SHA256 of the person's id under AppConfig:AI:Erasure:SubjectReferenceKey (base64, at least 32 bytes): whoever holds the key can recompute it from an id and find that person's erasure, and no one without the key can reverse it. Without a key, no reference is recorded. A missing key, a broken audit sink or a broken compliance trail never blocks an erasure: the failure is logged and the erasure goes on. Log lines on the erasure path carry neither the person's id nor their conversation or memory ids.

i
Every record is kept in the compliance audit trail

Each record is written twice, independently (#969). IComplianceAuditTrail keeps it in the compliance audit trail: hash-chained JSONL day-files under {AppConfig:AI:Erasure:AuditStoragePath}/compliance (by default .agent-sessions/compliance), walked by scheduled chain verification and moved to the archive with the other trails when AppConfig:AI:Audit:ArchivePath is set. Nothing deletes it, and erasure lists it on every receipt as RetainedByObligation rather than erasing from it. The audit sink, StructuredLogAuditSink by default, also writes it as one log line for log tooling; that line is deleted with the logs after Logging:Retention:RetainFor, 30 days by default. Export (subject_access_export) and document-removal (document_removal) records are kept the same way. Startup refuses an empty AuditStoragePath. The compliance report summarises the trail for its period: counts by request and outcome, and each finished request's receipt id, with no operator, subject or document reference (#1000); records still held for replay are named in its warnings.

i
A record the trail cannot write is held, then written

When the trail cannot be appended to (its chain lock still busy, a full disk, a folder it may not write), the record is held in {AuditStoragePath}/compliance-pending instead of surviving only as the error log line (#995). An erasure or export is not kept waiting for the lock: its record waits at most half a second, rather than the writer's usual ten, before it is held (#999). The other five audit trails hold and replay the same way, each in a -pending folder beside its own day-files, such as governance-pending (#1001); a trail that refuses the action when its record cannot be written (changes, egress, escalations, a drift operator's attempt) still refuses it. Changes and egress hold the decision marked not_carried_out, which the report and the audit queries honour; the escalation trail holds only execution reports and the drift trail no operator attempt, since those callers refuse or re-drive the rest themselves. A pass writes at most 500 held records, oldest first, and sets aside a held file over 1 MiB or one whose name carries no hold time; agent.audit.records_held reports what is still waiting. Each held file is the exact line the trail refused, with an operator already replaced by their keyed reference, so it holds nothing the trail would not; it is flushed to disk and renamed into place before the request returns (the rename itself is not forced to disk, so on Linux a power cut at that moment can still lose it; a process crash cannot). A held file one pass cannot read is left for the next, and the files behind it go ahead. Anything that can write this folder can add a record to the trail, as anything that can write the trail's own folder can; both are made owner-only. A background service writes held records into the trail when the host starts and every minute, oldest first, and removes each file only once its record is in the trail. A pass first looks for every held line in the trail and only removes those already there, so a crash between writing and removing never writes a record twice, and an exclusive lock in the folder stops hosts that share it from replaying the same record. The trail is in the order records were appended: a replayed record keeps its own timestamp and correlation_id but can sit after records made later, so order requests by timestamp. Every record that could not be written is counted on agent.audit.write_failures, tagged with its trail (agent.audit.chain) and agent.audit.outcome: pending when it is held, lost when it could not be held either (logged as critical; alert on it), stuck when a held file cannot be opened (another account owns it, another process keeps it open), counted and logged as an error once per file in each process rather than on every pass, so it too means a record missing from the trail, and agent.audit.records_replayed counts the held records written since. The folder is on the trail's volume, so a full or read-only volume usually refuses the held file as well; holding mainly covers a busy lock and passing I/O failures. A held file that is not a record is renamed .unreadable, counted as lost and left for an operator.

Deleted text on disk

SQLite normally marks a deleted row's space free without clearing it, so erased text could still be read from the database file. Every SQLite connection the harness opens turns PRAGMA secure_delete on, through SqliteSecureDelete and UseSqliteWithSecureDelete, and the full-text index also sets FTS5's own secure-delete option so deleted words leave its index immediately. The databases run in write-ahead-log mode, where a deletion first lands in a side log and the old page stays in the main file until a checkpoint, so once every store has deleted, each SQLite store empties its log (wal_checkpoint(TRUNCATE), through IPersonalDataScrubber). This is a separate pass, on every request: when another connection is mid-read and a log cannot be emptied, the receipt gets its own Failed "(deleted bytes)" line without marking the delete itself failed or holding back the stores after it, and a retry empties the log even though there is nothing left to delete. A test erases a person and scans the database files and their logs for their text while the host's connections are still open. Limits:

  • It covers deletes from now on. Rows deleted before this change can remain in free pages until a one-time VACUUM of each database; for the full-text index, run its optimize (or rebuild) command first, because words of rows deleted before secure-delete was on sit in live index segments, which VACUUM keeps.
  • Copies outside the database file are out of its reach: backups and snapshots taken before the erasure, and blocks the file system has not reused. Retention of backups is an operational control.
  • With FTS5 secure-delete in use, the full-text database can no longer be read by SQLite older than 3.42; the bundled SQLite is newer.
  • External stores (Azure AI Search, PostgreSQL, Neo4j) manage their own storage and deletion guarantees.

Right of access and portability (GDPR Articles 15 and 20)

POST /api/compliance/export-my-data returns a machine-readable copy of everything the harness can find for the signed-in person, as a JSON file (#902). Like erase-my-data it takes no owner parameter: the subject is always the caller. It is refused, and the refusal recorded, while sign-in is bypassed (every caller is then one synthetic person, so the copy would hold everyone's data) and for an application's own token. It is limited to five requests an hour per person, and the host assembles at most two copies at once; a further request is refused with 429 rather than queued. The copy holds only what the host it was sent to can find, and its host field says which host that is. Ask each host that holds personal data (see above).

For someone who cannot sign in. POST /api/compliance/exports with the person's id in the body (never the URL, so it stays out of access logs) returns the same copy and manifest, for an operator to pass on. The same gate as operator erasure decides who may ask: the Harness.Compliance.ExportSubject role, a separate grant from erasure because reading a person's whole data and deleting it are different responsibilities, which no development identity carries; sign-in from a tenant listed in AppConfig:AI:Erasure:OperatorTenantIds (empty means off); and never while sign-in is bypassed. Every request that reaches it, refused or not, is audited with the operator's id and the person's pseudonymous reference only. Each operator may ask thirty times an hour, and their copies count against the same host-wide limit as everyone else's. Give the id exactly as the identity provider issues it: a re-cased id finds no conversations or documents, and the copy would be empty while looking complete.

What the copy holds. One section per store that can return a person's data: their conversations with every message, their schedules, their workflow and evaluation run records (finished or still live) with each evaluation's dataset names, options and report (#991), their bundle runs with the messages they sent and the agent's answers, the bundles they staged (which agent, skills and plugins, not where the host extracted them) (#990), and their knowledge-graph nodes and edges, including remembered facts the write-gate quarantined, which the product never shows them but which are still theirs. A record with no owner is shared or global and is never included on its own, and neither is an edge another person owns, even where it touches this person's node. An unowned edge is included only between two of the person's own nodes: one from their node into shared knowledge is usually document ingestion's, carrying the organisation's document text, so it is left out even though erasure removes it with the person's node. Every store matches the person across all tenants, which relies on the identity provider's user id being unique across them, as erasure does.

Planned tasks too. Their plans, with each step's configuration (a model step's prompt included), output, error and attestation, the plan's execution log and every run they made; a run they made on someone else's shared sub-plan is included as the run record alone, without that plan. The tool output spilled to disk for their conversations and for their planned tasks' steps, as stored, which is after secret redaction. When the observability database is switched on, the person's part of what it recorded for their conversations and their planned tasks' model steps: their messages, the tools run for them and what those returned, each session's timing, model and token counts, safety-check outcomes, and which operations were audited and when. A planned task's steps ran under ids of their own that only the plan store's record of the run leads to, so the copy reads the person's runs the way erasure does, together with what an unfinished erasure request recorded.

The operator's material stays out. The observability database also records what today only the observer role may read: the registration bodies loaded for each turn (system prompt, skill instructions, tool and MCP descriptions), the per-turn context inventory, system-context and hook-injected messages, raw error text, cost figures, safety filter names and audit metadata, which can name other people such as an approver. None of it is in the copy, which names its columns one by one, so a column a later migration adds reaches people only when it is added on purpose. Erasure still deletes all of it with the person's conversations.

Documents they loaded. Every chunk the document indexes hold under the person's stamp, in every collection: its text, the document and section it came from, and, for the in-memory index, its source. Not the embeddings, which are derived vectors of the same text, and not the owner and tenant stamps. A chunk loaded without an identity carries no stamp and is not in anyone's copy, as it is not in anyone's erasure. Azure AI Search backs both its vector and its keyword store with one index, so that index is read once. Its reader pages in chunk-id order, starting each page after the last id read, so every chunk is read once however many there are, and checks the result against the total the service reports; a read that cannot be confirmed complete is a failed line, never a copy with chunks silently missing. This needs the index's id field sortable and filterable and its ownerId field filterable. Those are the REST API's defaults for string fields, but an index defined with the .NET SDK's SimpleField must set IsSortable on id, or every export reports that store as failed.

What they remember and taught the agent. Their cross-session memories, from both places erasure purges them: the in-process cache and the durable graph backend that keeps them across restarts (the SQLite graph.db, despite the class's Kùzu name), returned once each, as the cache holds a memory it has newer than the last sync. A memory id belongs to one owner: a write under an id another person already holds is refused, because the backend keeps the owner it first stored, and an overwrite would otherwise put one person's words in the other's copy and erasure. Learnings they wrote are knowledge-graph nodes stamped with them, so they are in the knowledge-graph section with their other nodes; learnings captured by background work carry no owner and are in no one's copy.

What the manifest says. Every store erasure reaches or lists has a line: what it returned, or why it returned nothing. A store that can hold the person's data but cannot yet return a copy, one that failed, and a log nothing ages out all mark the copy incomplete (isComplete: false), so it never reads as everything while one of them holds the person's data. Stores whose records expire on their own, the tamper-evident audit trails and the organisation's documents are listed without doing so. Every store that can find and erase one person's data also returns it, unless it holds nothing a person would receive (the token-budget counters, listed as not applicable); a test holds every store's declaration to that. A host running a replacement that cannot, such as the remote cross-session memory stand-in, has it named here. If the record of the person's planned-task runs or of an unfinished erasure cannot be read, that is a failed line too, because what only it leads to is then missing from the copy.

Delivered at once, never stored. The copy is assembled for the request and returned as its response, marked Cache-Control: no-store. An export job that wrote an archive for later download would be one more store of the person's whole data, needing its own retention, erasure and access control and a download link nobody could guess. The trade-off is that a very large copy is held in memory while the request runs, under the same ten-minute limit as erasure. A copy is not made while an erasure for the same person is running: both take the same per-person turn. That turn is held in one process, like the erasure journal's hold, so behind several instances an export can overlap an erasure running on another and miss what it was deleting.

Audit. Each request writes an Attempted and an outcome record with the action subject_access_export, in the same shape as erasure's: who asked, the pseudonymous subject reference, the copy's request id, whether it is complete, and each store's status and record count. Never the person's id, and never anything the copy contains. Like erasure's, the records are kept in the compliance audit trail as well as written to the log.

Data-classification DLP

Isolation and retention govern where data lives; data-loss prevention governs whether a tool call may move it at all based on its sensitivity. The harness ships a Microsoft Purview classification gate, IToolClassificationGate, that runs on the live tool-execution path — one of the three ambient gates inside GovernedAIFunction (see Tools & Permissions). It classifies the data a tool touches against Purview sensitivity labels and acts on the verdict.

It is opt-in through a single mode knob, AppConfig:AI:Governance:DataClassification:Mode:

  • Off (default) — the gate is inert; no classification runs.
  • Audit — classifications are computed and logged, but nothing is blocked or altered.
  • Enforce — verdicts act. A Block verdict returns a model-facing message instead of running the tool; a RedactOutput verdict lets the tool run, then scrubs the result through ICompositeResponseSanitizer and additionally through IContentRedactionFilter's known-secret-pattern scrub — strictly more than the unconditional sanitize every other tool result already gets — before it re-enters the model's context.

The gate fails open on ambiguity by design: an Unknown classification maps to Allow, and the whole subsystem stays dormant unless both a mode other than Off and a classification provider are configured. This keeps the closed-by-default posture on capabilities while avoiding false positives that would block legitimate work in deployments that have not adopted Purview labelling.

Data at rest: what the harness does not encrypt

The harness does not encrypt the files it keeps personal data in. Its local stores are plaintext on disk: SQLite databases, the knowledge-graph files, JSONL audit trails, log files and spilled tool results. Owner-only file permissions are applied on Linux; on Windows the files inherit the folder's access control. Encryption at rest is therefore the deployer's job, and the usual answer is to encrypt the volume the data directory sits on.

The harness cannot detect whether a volume is encrypted, so it asks instead. Outside Development, a host warns at startup until the deployer records an answer in AppConfig:Infrastructure:DataAtRest:Encryption. Unspecified (the default) warns; Volume records that the volume is encrypted and is logged at Information. The check is DataAtRestStartupCheck (src/Content/Infrastructure/Infrastructure.AI/DataAtRest/DataAtRestStartupCheck.cs).

Where the data is Examples How to protect it at rest
Local SQLite databases Conversations and budgets, planner runs, prompt usage, schedules, the erasure journal, the document load ledger, the keyword index when it is file-backed Volume or disk encryption (BitLocker, LUKS, a cloud provider's disk encryption). The harness does not ship SQLCipher.
Local files JSONL audit trails, log files, file-system conversation transcripts, spilled tool results, the Kùzu graph Volume or disk encryption, on the same volume as the databases.
The audit archive Sealed audit segments copied off the host The storage service's own encryption at rest, for example Azure Storage's (see the audit archive).
PostgreSQL The observability store; the PostgreSQL knowledge-graph backend The database server's encryption at rest. A managed service such as Azure Database for PostgreSQL encrypts its storage; a self-hosted server needs disk encryption.
Other external services Neo4j, Azure AI Search, the distributed cache That service's encryption-at-rest setting. Check it for each one you configure.

Telemetry export from FoundryHost

Every host except FoundryHost exports to Azure Monitor only when AppConfig:Observability:Exporters:AzureMonitor:Enabled is set and a ConnectionString is given. Foundry injects APPLICATIONINSIGHTS_CONNECTION_STRING into every hosted container. By default FoundryHost turns the harness's exporter on with it, and the Foundry hosting layer (AgentHost) exports its own traces and logs to it as well, so telemetry goes to that Application Insights resource without any setting of the deployer's. FoundryHost says so at startup.

To send nothing there, set the opt-out to false. FoundryHost then removes the variable before anything reads it, so neither the harness nor the hosting layer exports to Foundry's resource, and Foundry's portal shows no traces for the agent. The harness's exporter is then yours to point at your own resource with Enabled and ConnectionString. What the telemetry may contain is governed by content capture and redaction, not by this switch.

This is the one description of where the opt-out can be set; the code and the startup message point here. FoundryHost reads it from the same configuration the host binds, and each source spells the setting differently:

  • appsettings or User Secrets (JSON): "AppConfig": { "Observability": { "Exporters": { "AzureMonitor": { "EnableFromHostConnectionString": false } } } }
  • Environment variable: AppConfig__Observability__Exporters__AzureMonitor__EnableFromHostConnectionString=false (double underscores; a variable name containing : is not portable).
  • Azure Key Vault secret: named AppConfig--Observability--Exporters--AzureMonitor--EnableFromHostConnectionString with the value false (Key Vault does not allow : in a name; the loader maps -- to it).
  • Azure App Configuration key: AppConfig:Observability:Exporters:AzureMonitor:EnableFromHostConnectionString, unlabelled or labelled API. Keys under any other label are not read.

Key Vault and App Configuration are read only in a Release build, only when the host has their address (AzureKeyVaultUri, AzureAppConfigConnectionString), and not when DisableAzureConfigSources is set. An opt-out placed in a source the host does not read has no effect, and FoundryHost's startup message says which way it went.

What the deploying organisation must do

The harness supplies mechanisms: an inventory of where personal data is kept, erasure and export that report honestly on every store, retention periods, pseudonymous audit references and the startup warnings on this page. It cannot make a deployment lawful. Under the GDPR the deploying organisation is the controller (or a processor acting for one), and these remain its job:

  • Lawful basis (Article 6). Decide and record the basis for each purpose the agent serves, and for any special-category data it may see (Article 9).
  • Privacy notice (Articles 13 and 14). Tell people what the agent keeps, for how long, who it is shared with, and how to ask for a copy or erasure. The retention periods and the receipt statuses on this page are the facts to draw on.
  • Processor agreements (Article 28). Have a data processing agreement with every service the deployment sends personal data to: the model provider, Azure AI Content Safety, Azure Monitor, Azure AI Search, and any database or cache you host elsewhere.
  • Regions and transfers (Chapter V). Choose the region of each of those services, and put transfer safeguards in place where data leaves the EEA. FoundryHost sends telemetry to the Application Insights resource Foundry supplies unless you turn that off (see telemetry export).
  • Records of processing (Article 30). The personal-data inventory (every [PersonalDataStore] declaration) is a starting point for your record, not the record itself.
  • Data protection impact assessment (Article 35). An AI agent that remembers people across sessions is likely to need one. Use the threat model and this page as inputs.
  • Security of processing (Article 32). Encrypt data at rest (see above), keep authentication bypass off outside Development, turn on content safety if you need it, and turn on knowledge isolation if more than one tenant shares the host.
  • Breaches (Articles 33 and 34). Have a process to detect, assess and report a personal-data breach within 72 hours. The audit trails and telemetry help with detection; the process is yours.
  • Requests from people (Articles 15 to 22). Decide who handles access and erasure requests, set AppConfig:AI:Erasure:OperatorTenantIds so operators can act for people who cannot use self-service, and keep the receipts.

This is a checklist, not legal advice. Agree each item with your data protection officer.

Secrets management

The data the agent holds is one thing; the credentials that let it reach databases, model endpoints, and APIs are another. None of them belong in source. Configuration is assembled by LoadAppConfig in src/Content/Presentation/Presentation.Common/Helpers/AppConfigHelper.cs, which layers sources in ascending priority — later layers override earlier ones:

appsettings.json
  -> appsettings.{Environment}.json
  -> User Secrets (development only)
  -> environment variables
  -> Azure Key Vault (non-DEBUG builds only)
  -> Azure App Configuration

Key Vault is wired in for non-DEBUG builds via:

builder.Configuration.AddAzureKeyVault(
    new Uri(akvUri),
    new DefaultAzureCredential());

The credential is DefaultAzureCredential — authentication is Entra managed identity, with no stored credential anywhere in the app to leak. No secret is hardcoded, and a missing required secret fails host startup loudly rather than letting the app run in a half-configured state. The Key Vault settings are bound through src/Content/Domain/Domain.Common/Config/Azure/KeyVaultConfig.cs.

i
This page is the application side; deployment is elsewhere

Here we cover how the app consumes secrets. The deployment side — provisioning the vault, assigning the managed identity, and granting it least-privilege access — lives in the Architecture guide: Networking & Security.

Attack scenario: reaching across the tenant wall

✕
A user tries to recall another tenant's data

Suppose a user in tenant A crafts a request designed to pull back a fact they know exists in tenant B — perhaps they learned a competitor's record id, or they try to address a memory key by guessing its name. Their request is authenticated as a tenant-A user, and that identity is set in the AsyncLocal accessor at the middleware before any retrieval runs.

When retrieval reaches the graph, every candidate record passes through TenantIsolatedGraphStore's per-record check. Tenant B's nodes have TenantId = B, which does not match the caller's tenant — the tenant check fails and those nodes are filtered out before they ever reach the model's context. The query returns nothing across the wall. Even the namespaced memory id (memory:B:…) can't be reached, because the caller's scope is A and the id space is partitioned by scope. No leak, no error message that confirms the record exists — just an empty, scoped result.

That closes the seventh and final layer. With identity, autonomy, tool permissions, execution, egress, content safety, and now data protection all in place, the last question is how you prove they stay in place release after release. That is the job of the OWASP Agentic evaluation pack — ten deterministic tests, one per threat category, that attack each layer and fail the build if a defence has quietly regressed.